12
votes

I have a UISearchBar on my MKMapView that I'm going to use to search annotations. I'm having trouble getting the cancel button to work. I create the search bar in my viewDidLoad method like this:

UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.frame = CGRectMake(0, 0, 320,44);
    searchBar.showsBookmarkButton = NO;
    searchBar.showsCancelButton = YES;
    [self.view addSubview:searchBar];

And I've implemented this method for the cancel button:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

What am I doing wrong?

2

2 Answers

16
votes

You haven't assigned the search bar delegate.

searchBar.delegate = self
2
votes

Please set delegate to self as in code i posted because search bar is unable to find delegate through which it calls the cancel button method.

searchBar.delegate=self;

and in .h file set the delegate as <UISearchBarDelegate>

Hope this helps.