In the contacts app on the iPhone if you enter a search term, then tap the "Search" button, the keyboard is hidden, BUT the cancel button is still enabled. In my app the cancel button gets disabled when I call resignFirstResponder.
Anyone know how to hide the keyboard while maintaining the cancel button in an enabled state?
I use the following code:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
The keyboard slides out of view, but the "Cancel" button to the right of the search text field is disabled, so that I cannot cancel the search. The contacts app maintains the cancel button in an enabled state.
I think maybe one solution is to dive into the searchBar object and call resignFirstResponder on the actual text field, rather than the search bar itself.
Any input appreciated.
Here's a slightly more robust solution that works on iOS 7. It will recursively traverse all subviews of the search bar to make sure it enables all
UIControl
s (which includes the Cancel button).Just call this method immediately after you call
[self.searchBar resignFirstResponder]
like this:Voila! Cancel button remains enabled.
I found a different approach for making it work in iOS 7.
What I'm trying is something like the Twitter iOS app. If you click on the magnifying glass in the Timelines tab, the
UISearchBar
appears with the Cancel button activated, the keyboard showing, and the recent searches screen. Scroll the recent searches screen and it hides the keyboard but it keeps the Cancel button activated.This is my working code:
I arrived at this solution by setting a breakpoint at my table view's
scrollViewWillBeginDragging:
. I looked into myUISearchBar
and bared its subviews. It always has just one, which is of typeUIView
(my variablesearchBarSubview
).Then, that
UIView
holds anNSArray
calledsubviewCache
and I noticed that the last element, which is the third, is of typeUINavigationButton
, not in the public API. So I set out to use key-value coding instead. I checked if theUINavigationButton
responds tosetEnabled:
, and luckily, it does. So I set the property to@YES
. Turns out that thatUINavigationButton
is the Cancel button.This is bound to break if Apple decides to change the implementation of a
UISearchBar
's innards, but what the hell. It works for now.You can create your CustomSearchBar inheriting from UISearchBar and implement this method:
As of iOS 6, the button appears to be a UINavigationButton (private class) instead of a UIButton.
I have tweaked the above example to look like this.
However, this is obviously brittle, since we're mucking around with the internals. It also can enable more than the button, but it works for me until a better solution is found.
We should ask Apple to expose this.
SWIFT version for David Douglas answer (tested on iOS9)
Building on smileyborg's answer, just place this in your searchBar delegate:
This solution works well on iOS 7 and above.