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?
For string comparison you should use
if([SearchBar.text isEqualToString: @""])
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
精彩评论