In this course I will show you how to create a searchable table view in Xcode 5.1 and iOS 7. The app will also be compatible with iOS 6.
There are six parts in total:
- Part 1: an overview of what we’d like to achieve
- Part 2: we’ll build the table view and populate it with dummy data
- Part 3: hooking up the UISearchDisplayController
- Part 4: displaying search results
- Part 5: hiding the UISearchBar when the app launches (and activating it with a button)
- Part 6: hiding the search bar in iOS 6
The whole course is about one hour in total. Enjoy!
Part 1: Overview
Podcast: Download (Duration: 13:55 — 145.2MB)
There is a new version of this article available as a screencast for iOS 7:
We’ve recently discussed how to deal with a Search Bar and Search Display Controller using Interface Builder. You can however do this in code too. This can be useful if you don’t want to make all the relevant connections in every Storyboard.
This example assumes you have a Table View (self.tableView) to which you’d like to add a Search Bar and Search Display Controller at the top. We do this by utilising the Table View’s tableHeaderView property:
// create a new Search Bar and add it to the table view
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
self.tableView.tableHeaderView = searchBar;
// we need to be the delegate so the cancel button works
searchBar.delegate = self;
// create the Search Display Controller with the above Search Bar
self.controller = [[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
self.controller.searchResultsDataSource = self;
self.controller.searchResultsDelegate = self;
Your View Controller also needs to conform to the UISearchBarDelegate Protocol for this to work properly.
If you add a UISearchBar to your table view (see previous article) it’s just sitting there by default. Chances are you’d like to hide it when your table view first loads.
You can do this by adding the following method, and call it whenever you’d like to make it disappear (call it from your viewDidLoad method for example, or via an observer from another class):
This content is for members only.
The ingredients for a search function in a UITableView are more involved than just displaying a simple search field. First we need the standard UITableView. Next we need a UISearchBar which can be added to the top of the table view. But displaying the actual search results is something called the UISearchDisplayController.
This process isn’t very well documented from what I could find, so here’s how I did it successfully. Works fine in iOS 6.
For iOS 5 compatibility please see my comment at the end.
An updated version for iOS 7 is also available. I’ve recorded a screencast about this here: