UISearchController: show results even when search bar is empty

optimus picture optimus · Jun 11, 2015 · Viewed 23.4k times · Source

As I understand, the default behaviour of UISearchController is:

  1. On tapping search bar, background is dimmed and 'cancel' button is shown. SearchResultsController is not shown till this point.
  2. SearchResultsController is displayed only if search bar is not empty.

I want to display SearchResultsController even when search bar is empty but selected (i.e is case 1 above).

Simply put, instead of background dimming, I would like to show Search results.

Is there a way for doing this?

More Clarification:

I am not using UISearchController to filter results shown on the view on which it is shown, but some other unrelated results. It will be like what facebook does on its 'News Feed'. Tapping on search bar shows search suggestions initially and then, when we start editing, it shows search results which might not be related to news feed.

Answer

Ken Toh picture Ken Toh · Mar 13, 2016

You can simply implement the UISearchResultsUpdating protocol and set the results controller view to always show in updateSearchResultsForSearchController:

 func updateSearchResultsForSearchController(searchController: UISearchController) {

   // Always show the search result controller
   searchController.searchResultsController?.view.hidden = false

   // Update your search results data and reload data
   ..
}

This works because the method is called even when the search bar is activated, without any text.