Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searchBarTextDidBeginEditing delegate method called two times

I'm debugging my code, where UISearchBar's delegate method searchBarTextDidBeginEditing: is called exactly twice every time I tap on the search bar (which is in the navigation bar).

The odd thing is that only this delegate method is called twice. The others are called only once within the whole proccess, which is the correct behavior.

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    // called only once
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    // called twice every time
    [searchBar setShowsCancelButton:YES animated:YES];
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    // called only once
    [searchBar setShowsCancelButton:NO animated:YES];    
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    // called only once        
}

Any idea what could be wrong?

The UISeachrBar is set up in Storyboard, with properly connected outlets, although it's not added to any view, and in the particular view controller's viewDidLoad is the following line that adds the search bar to the navigation bar:

self.searchDisplayController.displaysSearchBarInNavigationBar = YES;

I'm using Xcode 5.0.1 and running the code in iOS 7.0.3 Simulator.

like image 460
Tom Kraina Avatar asked Nov 10 '13 13:11

Tom Kraina


1 Answers

I was experiencing the same issue, and dug in a bit deeper.

In my case, I had a subclass of UISearchDisplayController which functioned as UISearchDisplayDelegate for itself, and UISearchBarDelegate for its UISearchBar.

As it turns out, the problem is that UISearchDisplayController implements the following methods that collide with theUISearchBarDelegate` protocol:

- (void)searchBar:(id)arg1 textDidChange:(id)arg2;
- (void)searchBarCancelButtonClicked:(id)arg1;
- (void)searchBarResultsListButtonClicked:(id)arg1;
- (void)searchBarSearchButtonClicked:(id)arg1;
- (void)searchBarTextDidBeginEditing:(id)arg1;

This means if you make a UISearchDisplayController the delegate of its own UISearchBar, those methods will be called twice.

like image 198
Bart Vandendriessche Avatar answered Oct 18 '22 03:10

Bart Vandendriessche