A simple tutorial of UISearchDisplayController (iOS 3-7)
After several years, thanks to StoryBoard and iOS 7, it becomes super easy to use Search Display Controller now.
I attached a new sample project here, hope it could help everyone who needs it.
I find out that, the API for UISearchDisplayController in SDK 3.0b is different from 3.0. And there’s no sample code for UISearchDisplayController anywhere else until now. (Yes, there is one in Apple’s sample code web page, but it uses Interface Builder to realize it. And there is one from the source code of “three20”, but it’s based on SDK 3.0b. )
So I wrote this sample based on “Table Search” sample code.It realizes UISearchDisplayController programmatically without Interface Builder. It supports landscape screen and search scopes, and integrate one UITabBarController with two UITableViewControllers.
Here is the tutorial.
- Declare an instance of UISearchDisplayController and set as property.
- Prepare two arrays to hold original data and filtered data.
- Set up viewDidLoadmethod
- Create an UISearchBar.
- Initialize the UISearchDisplayController based on the UISearchBar:
1 [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];
- Set the UISearchDisplayController instance:
1 2 3 [self setSearchDisplayController:searchDisplayController]; [searchDisplayController setDelegate:self]; [searchDisplayController setSearchResultsDataSource:self];
- Set up UISearchDisplayController delegate methods:
1 2 3 - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption - (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
Be careful, we need to set the delegate for self.searchDisplayController.searchResultsTableView each time we begin to search. Because the instance of searchResultsTableView is allocated and released automatically.
- Set up UITableView data source and delegate methods, we distinguish filtered or not filtered table by
1 if (tableView == self.searchDisplayController.searchResultsTableView)
- Remember to return YES in shouldAutorotateToInterfaceOrientation to support landscape screen.
Some details need to be cared:
- self.searchDisplayController.searchResultsTableView is created and release automatically, so its delegate should be setted each time it’s created.
- Every time we turn to a landscape UITableViewController, the UISearchBar in the tableHeaderView has only a width of 320 even we have already setted sizeToFit. It’s may be caused by UITabBarController, I don’t know. So I set the frame of tableHeaderView based on the screen orientation manually in the viewDidLoad method.