How to access searchBar's clear text button?

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?

Answers


For string comparision u 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


Need Your Help

jms call to message.acknowledge() after exiting onMessage()

java concurrency jms

I want to concurrently consume jms messages from multiple queues. All the messages should go to the DB after long running processing and I have no right to lose them.

Drupal: Duplicate blog tags showing in block

php drupal drupal-views

I've got a Druapl-based website with a blog. I'm using a custom view block to list the different tags I've assigned to my posts. Although it lists them just fine (links work fine too), I'm gettin...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.