Question

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?

Was it helpful?

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.

OTHER TIPS

Updated for switf 3:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == ""
    {
       searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1)
    }
}

Add Cancel Button to View load and add method -> searchBarCancelButtonClicked

searchBar.showsCancelButton = true

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  searchBar.resignFirstResponder()
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSRange foundRange = [searchText rangeOfString:@"x"];
if (foundRange.location != NSNotFound) {
    if (searchText.length == 0) {
        [searchBar resignFirstResponder];
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top