iOS 11 SearchBar in NavigationBar

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.


You can change the height of UISearchBar in iOS 11 by adding a constraint of height 44:

if #available(iOS 11.0, *) {
    searchBar.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
}