iOS 7 UISearchBar Issue

Dear all,

Transition into iOS 7 introduces a lot of adjustments. One such adjustment is the UISearchBar.

If you try to set the UISearchBar to the NavigationBar inside a UIViewController, then it will not work correctly in iOS 7.

The workaround for that is to use a UISearchDisplayController. Here are the steps.

1. Create your UISearchBar

UISearchBar *newSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
newSearchBar.showsCancelButton=YES;
newSearchBar.delegate=self;

2. Create a UISearchDisplayController and initialise with the UISearchBar & your ViewController

UISearchDisplayController *searchDisplayController=[[UISearchDisplayController alloc] initWithSearchBar:newSearchBar contentsController:self];

3. Set the datasource & delegates of the UISearchDisplayController

searchDisplayController.delegate=self;//The delegate of UISearchDisplayController
searchDisplayController.searchResultsDataSource=self;//The data source for the search results tableView
searchDisplayController.searchResultsDelegate=nil;

4. Now, enable search bar display in the navigation bar

searchDisplayController.displaysSearchBarInNavigationBar=YES;

5. Now, in your ViewController, implement the datasource & delegate protocols

#pragma mark - UISearDisplayController delegate methods
-(void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView {

tableView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0];
tableView.frame=CGRectZero;//This must be set to prevent the result tables being shown

}

#pragma mark - UITableView data source methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

return 0;//To make an empty table
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 0;
}

Hope this works for you.

Comments

Anonymous said…
I built my view in storyboard. Place the search bar with search display controller under the navigation bar just above my table view. now when i set displaysSearchBarInNavigationBar to YES the search bar positions it self in the middle of the view.