I have a UISearchBar which acts as a live filter for a table view. When the keyboard is dismissed via endEditing:, the query text and the gray circular "clear" button remain. From here, if I tap the gray "clear" button the keyboard reappears as the text is cleared.
How do I prevent this? If the keyboard is not currently open I want that button to clear the text without reopening the keyboard.
There is a protocol method that gets called when I tap the clear button. But sending the UISearchBar a resignFirstResponder message doesn't have any effect on the keyboard.
Best Answer
This is an old question and I just came across the same issue and managed to solve it the following way:
When the
searchBar:textDidChange:
method of the UISearchBarDelegate gets called because of the user tapping the 'clear' button, the searchBar hasn't become the first responder yet, so we can take advantage of that in order to detect when the user in fact intended to clear the search and not bring focus to the searchBar and/or do something else.To keep track of that, we need to declare a
BOOL
ivar in our viewController that is also the searchBar delegate (let's call itshouldBeginEditing
) and set it with an initial value ofYES
(supposing our viewController class is called SearchViewController):Later on, in the UISearchBarDelegate, we implement the
searchBar:textDidChange:
andsearchBarShouldBeginEditing:
methods:Basically, that's it.
Best