iOS 11 SearchBar in NavigationBar

PatrickDotStar picture PatrickDotStar · Jul 27, 2017 · Viewed 35.5k times · Source

With iOS 11 Apple has redesigned the UISearchBar by making the corners rounder and the height bigger. Adding a UISearchBar to the navigationBar is pretty simple by just setting it as the titleView of the navigationItem using navigationItem.titleView = searchBar.

However, in iOS 11 it does not seem to work anymore as expected. Have a look at the screens where we compare the same setup using iOS 10 and iOS 11

iOS 10 enter image description here

iOS 11 enter image description here

You can clearly see that the SearchBar increases the size of the NavigationBar but the bar buttons do not get aligned correctly. Also the searchBar does not use the available space on the left anymore.

Putting the searchBar into a wrapper view to get the cancel button on iPad as described here Cancel button is not shown in UISearchBar also does not seem work anymore since the searchBar is then not visible at all.

If anyone has similar issues or already knowns how to fix/improve this I would be very thankful.

This was built using Xcode 9 Beta 4. Maybe future releases will fix this issue.

UPDATE:

Since this does not get fixed we decided to use following solution. We added a new UIBarButtonItem to the NavBar which then presents a new ViewController where we only put a searchBar and nothing else into the NavBar which seems to work. Using the selected answer may be the best solution since Apple with iOS 11 wants us to use this new design even if it does not give us the result we originally wanted. Another way to possible solve this could be a custom SearchBar but this is another topic.

Answer

Justin Domnitz picture Justin Domnitz · Aug 22, 2017

There's a new searchController property on navigationItem in iOS 11.

https://developer.apple.com/documentation/uikit/uinavigationitem/2897305-searchcontroller

Use like this...

if #available(iOS 11.0, *) {
     navigationItem.searchController = searchController
} else {
     // Fallback on earlier versions
     navigationItem.titleView = searchController?.searchBar
}

In Objective-C the if statement looks like this:

if (@available(iOS 11.0, *)) {

On iOS 11, if you don't set navigationItem.hidesSearchBarWhenScrolling = false, the search bar may initially be hidden, unless the user scrolls down to reveal it. If you do set it to false, it appears stacked below where the title would go without the user having to scroll.