3

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?

bruno
  • 2,154
  • 5
  • 39
  • 64
  • You have the answer [here][1] in other stackoverflow post [1]: http://stackoverflow.com/a/4200431/921789 – Fran Martin Mar 04 '14 at 16:01
  • That one didn't really worked for me. This one was better http://stackoverflow.com/a/9084809/516765 – bruno Mar 04 '14 at 16:12

4 Answers4

11

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.

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
7

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)
    }
}
Nathan
  • 11,938
  • 12
  • 55
  • 62
Ammad
  • 341
  • 6
  • 7
1

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

searchBar.showsCancelButton = true

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  searchBar.resignFirstResponder()
}
user3826696
  • 1,045
  • 12
  • 13
0
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSRange foundRange = [searchText rangeOfString:@"x"];
if (foundRange.location != NSNotFound) {
    if (searchText.length == 0) {
        [searchBar resignFirstResponder];
        }
    }
}
sangony
  • 11,636
  • 4
  • 39
  • 55