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):
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.
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.
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.
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.
When results are empty, UISearchController
's viewController
is still hidden. That's why we have to fiddle our way around using UISearchControllerDelegate
's willPresentSearchController:
self.searchController
make your ViewController conform to `UISearchControllerDelegate:self.searchController.delegate = self;
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.
didPresentSearchController:
for sanity:- (void)didPresentSearchController:(UISearchController *)searchController
{
searchController.searchResultsController.view.hidden = NO;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With