Show UISearchController's SearchResultsController on SearchBar Tap

Attiqe picture Attiqe · Mar 22, 2015 · Viewed 8.4k times · Source

I am using UISearchController not UISearchDisplayController, and I want to show SearchResultController on SearchBar Tap right away. Right now it's showing like this (when I tap on the search bar):

Answer

bhr picture bhr · Mar 22, 2015

When results are empty, UISearchController's viewController is still hidden. That's why we have to fiddle our way around using UISearchControllerDelegate's willPresentSearchController:

After initializing self.searchController make your ViewController conform to `UISearchControllerDelegate:

self.searchController.delegate = self;

Implement willPresentSearchController: in your ViewController:

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

The async dispatch is necessary, because otherwise it will be overridden by the internal behavior. You could go fancy here and use an animation to have the table view fade in.

Additionally, implement didPresentSearchController: for sanity:

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