Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show UISearchController's SearchResultsController on SearchBar Tap

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):

like image 984
Attiqe Avatar asked Mar 22 '15 16:03

Attiqe


People also ask

What is the uisearchcontroller in iOS?

The UISearchController was introduced a couple years ago in iOS 8 to replace the now deprecated UISearchDisplayController. In the new search controller, it is easier to add search to your table views.

How to show search results in a different view controller?

The initializer to UISearchController can take an argument that can specify a different view controller to show the search results. I think the most common use case is to show the search results in the same view controller that has the table view.

Is it too much work to add a uisearchcontroller?

Hopefully you found that it was not too much work to add a UISearchController. Once Apple updates Interface Builder to include the UISearchController, it should be even less code.

Where does the search bar appear on the list?

When we run the app now, you can see the search bar appears at the top of the list. As I type, I can see my table view update.


1 Answers

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;
}
like image 89
bhr Avatar answered Nov 16 '22 15:11

bhr