In my iOS app, I would like to have a right side search button in my UINavigationController
, and when a user touches the button, the UISearchBar
above my UITableView
is shown.
I would like the UISearchBar
hidden when the view loads, and then hidden again when the user clicks the Cancel button in the UISearchDisplayController
.
I've searched everywhere and cannot find an example. Help?
There is a nice sample project here. The key points are:
1.Hide the Search Bar before presenting the View:
-(void)viewWillAppear:(BOOL)animated {
[self hideSearchBar];
}
-(void)hideSearchBar {
CGRect newBounds = self.tableView.bounds;
newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
self.tableView.bounds = newBounds;
}
2.On the action target for your search button, display the Search Bar
// make the search bar visible
// code example from https://github.com/versluis/Table-Seach-2013 to deal with iOS 7 behavior
-(IBAction)displaySearchBar:(id)sender {
[self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
NSTimeInterval delay;
if (self.tableView.contentOffset.y >1000) delay = 0.4;
else delay = 0.1;
[self performSelector:@selector(activateSearch) withObject:nil afterDelay:delay];
}
- (void)activateSearch
{
[self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
[self.searchBar becomeFirstResponder];
}
3.Finally, hide the SearchBar when Cancel is clicked
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[self hideSearchBar];
}