None of the answers worked for me at all. I'm targeting iOS 7. But I found an answer.
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:
UIView *searchBarSubview = self.searchBar.subviews[0];
NSArray *subviewCache = [searchBarSubview valueForKeyPath:@"subviewCache"];
if ([subviewCache[2] respondsToSelector:@selector(setEnabled:)]) {
[subviewCache[2] setValue:@YES forKeyPath:@"enabled"];
}
I arrived at this solution by setting a breakpoint at my table view's scrollViewWillBeginDragging:
. I looked into my UISearchBar
and bared its subviews. It always has just one, which is of type UIView
(my variable searchBarSubview
).
Then, that UIView
holds an NSArray
called subviewCache
and I noticed that the last element, which is the third, is of type UINavigationButton
, not in the public API. So I set out to use key-value coding instead. I checked if the UINavigationButton
responds to setEnabled:
, and luckily, it does. So I set the property to @YES
. Turns out that that UINavigationButton
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.