optimus optimus - 5 months ago 97
iOS Question

UISearchController: show results even when search bar is empty

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

If your searchBar is active but has no text, the underlying tableView results are shown. That's the built-in behavior, and the reason why searchResultsController is hidden for that state.

To change the behavior when search is active but not filtering, you're going to have to show the searchResultsController when it is normally still hidden.

There may be a good way to accomplish this via <UISearchResultsUpdating> and updateSearchResultsForSearchController:. If you can solve it via the protocol, that's the preferred way to go.

If that doesn't help, you're left with hacking the built-in behavior. I wouldn't recommend or rely on it, and it's going to be fragile, but here's an answer if you choose that option:

  1. Make sure your tableViewController conforms to <UISearchControllerDelegate>, and add

    self.searchController.delegate = self;

  2. Implement willPresentSearchController:

    - (void)willPresentSearchController:(UISearchController *)searchController
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            searchController.searchResultsController.view.hidden = NO;
        });
    }
    

    This makes the searchResultsController visible after its UISearchController set it to hidden.

  3. Implement didPresentSearchController:

    - (void)didPresentSearchController:(UISearchController *)searchController
    {
        searchController.searchResultsController.view.hidden = NO;
    }
    

For a better way to work around the built-in behavior, see malhal's answer.

Comments