Use the following two methods in the UISearchBarDelegate
and do something like this:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
}
If you want the search to appear more responsive you can move your posted code to the searchBar:textDidChange:
delegate method and then only use searchBarSearchButtonClicked:
to do a [searchBar resignFirstResponder]
:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
_fetchedResultsController = nil;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error])
{
NSLog(@"Error in search %@, %@", error, [error userInfo]);
}
else
{
[self.timelineTableView reloadData];
[self.noResultsLabel setHidden:_fetchedResultsController.fetchedObjects.count > 0];
}
}
Additionally you can use the searchBarCancelButtonClicked:
to also resign the first responder from the search bar and then update your table view by calling the delegate searchBar:textDidChange:
:
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar setText:@""];
[self searchBar:searchBar textDidChange:@""];
[searchBar resignFirstResponder];
}