Question

When I hit the "clear" button (the one that appears when editing) on the tableView search, I was trying to get the keyboard to disappear. How can I detect when the "clear" button is clicked, so I can resign the firstResponder? I already tried this in the textDidChange method:

if (SearchBar.text == @"") {
    [SearchBar resignFirstResponder];
    NSLog(@"clear called");
}

which did not work...and also tried:

 if (SearchBar.text == nil) {
    [SearchBar resignFirstResponder];
    NSLog(@"clear called");
}

Neither methods show that they were called. Any ideas?

EDIT: Now resignFirstResponder does not seem to be working. The keyboard stays on screen. What's am I doing wrong?

Was it helpful?

Solution

For string comparison you should use

if([SearchBar.text isEqualToString: @""])

OTHER TIPS

You can try watching the text property of the search bar by registering for a KVO notification:

[self.searchBar addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:NULL];

and then implementing:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  if (object == self.searchBar && [keyPath isEqualToString:@"text"]) {
    // Handle the new value of self.searchBar.text
  }
}

Edit: nevermind, answered above =)

I know this question is old, but another way to do this is:

if(searchText.length == 0)

in - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top