Search code examples
iosuitableviewuisearchcontrollerios11iphone-x

iphone x: keep search bar within safe zone


Upgrading our application to support iPhone X. How can I add a search bar to the header of a table view and have it within the safe zone? Here is how we currently build the search bar.

let searchController = UISearchController(searchResultsController: nil)
func buildSearchBar() {
    self.searchController.searchResultsUpdater = self
    self.searchController.hidesNavigationBarDuringPresentation = false
    self.searchController.dimsBackgroundDuringPresentation = false
    self.searchController.searchBar.sizeToFit()
    self.tableView.tableHeaderView = searchController.searchBar

    self.definesPresentationContext = true
}

Solution

  • Unclear what you mean by "within the safe zone". The table view can scroll, so the search bar is not necessarily "within" any part of the screen; it can be scrolled up behind the sensor area and on beyond.

    You'll notice, however, that the native apps do not put the search bar as the header of the table. They put it in the navigation bar. You should do the same. Put the search bar into the navigation bar by setting the searchController of the navigationItem.