iosuisearchbaruikeyboardresignfirstresponder

Dismiss keyboard when pressing "x" in UISearchBar


If i put the resign code inside my if condition the keyboard doesn't resign, if i comment the if condition my keyboard resigns.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
        [searchBar resignFirstResponder];
    }
}

I want to resign the keyboard when the user presses the "x" button, which is when the UISearchBar text is empty. Is there a way to do this that works?


Solution

  • Just resign the first responder but in the next run loop like this:

    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
    {
        if ([searchText length] == 0) 
        {
            [searchBar performSelector:@selector(resignFirstResponder)
                       withObject:nil 
                       afterDelay:0];
        }
    }
    

    Tested and it works.