Tuesday, October 16, 2018

Hide Navigation Controller Search Bar & opened Large Title programmatically

Leave a Comment

I have a tableView. I set the all settings about searchController ( Search Bar in Large Navigation Bar ) - ( open / close when scroll tableview ). I implemented rightBarButtonItem which name is 'Close' . I want to hide/close tableView and Search Bar with programmatically. I can hide tableView but not SearchBar.

When I do isHidden for SearchBar , The Large Navigation Bar doesnt shrink to normal size.

Pic 1. Opened search bar with scroll down.

enter image description here

Pic 2. Not Hidden Large Navigation Bar with programmatically ( searchar.isHidden not implemented here )

enter image description here

Thanks in advance.

I tried this before but not run

tableView.setContentOffset(.zero, animated: false) navigationController?.navigationBar.prefersLargeTitles = false 

2 Answers

Answers 1

I tried to find a proper way to hide search bar, but I didn't find. But I found a workaround to hide your search bar which is change content offset your table view.

You may try this function to hide your table view and search bar.

func hide() {     tableView.isHidden = true     let point = tableView.contentOffset     let searchBarFrame = self.navigationItem.searchController?.searchBar.frame     let newPoint = CGPoint(x: point.x, y: point.y + searchBarFrame!.height)     tableView.setContentOffset(newPoint, animated: true) } 

Answers 2

Just try this:

 navigationItem.searchController = nil 

This is all my test code:

@IBOutlet weak var tableView: UITableView!  @IBOutlet weak var leftBarButtonItem: UIBarButtonItem!  var isHidden = false  var searchController: UISearchController {      let search = UISearchController(searchResultsController: nil)      search.searchBar.placeholder = "hello world"      search.obscuresBackgroundDuringPresentation = false      return search }   override func viewDidLoad() {     super.viewDidLoad()      self.navigationItem.title = "Test"      tableView.delegate = self      tableView.dataSource = self      showSearchController() }  @IBAction func isHiddenAction(_ sender: UIBarButtonItem) {     isHidden = !isHidden      self.tableView.isHidden = isHidden      if isHidden {         leftBarButtonItem.title = "Show"         hiddenSearchController()      } else {         leftBarButtonItem.title = "Hidden"         showSearchController()     } }  func hiddenSearchController() {     navigationItem.searchController = nil }  func showSearchController() {      navigationItem.searchController = searchController      navigationItem.hidesSearchBarWhenScrolling = true      definesPresentationContext = true } 

screenShots

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment