Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show search bar in navigation bar without scrolling on iOS 11

I’m attaching a UISearchController to the navigationItem.searchController property of a UITableViewController on iOS 11. This works fine: I can use the nice iOS 11-style search bar.

However, I’d like to make the search bar visible on launch. By default, the user has to scroll up in the table view to see the search bar. Does anyone know how is this is possible?

enter image description here enter image description here

Left: default situation after launch. Right: search bar made visible (by scrolling up). I’d like to have the search bar visible after launch, as in the right screenshot.

I already found that the search bar can be made visible by setting the property hidesSearchBarWhenScrolling of my navigation item to false. However, this causes the search bar to always be visible — even when scrolling down —, which is not what I want.

like image 285
Jonathan Avatar asked Sep 15 '17 12:09

Jonathan


2 Answers

The following makes the search bar visible at first, then allows it to hide when scrolling:

override func viewWillAppear(_ animated: Bool) {     super.viewWillAppear(animated)     if #available(iOS 11.0, *) {         navigationItem.hidesSearchBarWhenScrolling = false     } }  override func viewDidAppear(_ animated: Bool) {     super.viewDidAppear(animated)     if #available(iOS 11.0, *) {         navigationItem.hidesSearchBarWhenScrolling = true     } } 

Using isActive didn't do what I wanted, it makes the search bar active (showing cancel button, etc.), when all I want is for it to be visible.

like image 186
Jordan Wood Avatar answered Sep 19 '22 19:09

Jordan Wood


You can set the property isActive to true after adding the searchController to the navigationItem.

Just like this:

override func viewDidAppear(_ animated: Bool) {     super.viewDidAppear(animated)     searchController.isActive = true } 
like image 37
txaidw Avatar answered Sep 22 '22 19:09

txaidw