How to add a Search Display Controller to a UITableView (in code)

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.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.