I’ve been examining the new UISearchController API which replaces the UISearchDisplayController API that has been around since iOS 3. My immediate impression is that it drastically simplifies the task of managing a search bar and displaying search results.

You can have a UISearchController up and running with very little code. In the sample project I’ve put on GitHub which lists and searches through an array of countries, I’ve configured a UISearchController with the following code in my viewController viewDidLoad method:

self.countrySearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.hidesNavigationBarDuringPresentation = true
            controller.dimsBackgroundDuringPresentation = false
            self.countryTable.tableHeaderView = controller.searchBar
            return controller

Update: See this repo instead.

There are a few items to point out in this code:

  • nil is passed in the UISearchController initialiser so as to ensure that the results of the search are presented in the current viewController.
  • The frame of the searchBar must be set, otherwise it has a height of 0.
  • As per the above, the UISearchControllers searchBar is added to the tableHeaderView. There is no need to add a UISearchBar or UISearchDisplayController in Interface Builder.

The viewController must conform to UISearchResultsUpdating protocol, which contains a single method:

func updateSearchResultsForSearchController(searchController: UISearchController!)

When that method is called, search results are updated based on what String is held the searchController.searchBar.text variable.

It’s a remarkably simple API to use.