I'm trying to achieve the same effect as Apple's Contacts app (left screenshot). The cancel button in UISearchBar is enabled even when the keyboard is dismissed. My app behaves differently (right screenshot). The cancel button automatically becomes disabled when the keyboard is dismissed. The user is forced to tap the cancel button one time to enable it and then another time to actually trigger the dismissal. This is not good user experience. How would I always keep the cancel button enabled like Apple's Contacts app?
Technical Details:
I'm not using UISearchDisplayController
due to some design requirements. This is just a UISearchBar
with my own custom search controller. The cancel button is shown using [self.searchBar showsCancelButton:YES animated:YES]
. The keyboard is dismissed using [self.searchBar resignFirstResponder]
.
Here's a recursive solution that is working for me.
func enableButtons(_ view:UIView) { for subView in view.subviews { enableButtons(subView) } if let buttonView = view as? UIButton { buttonView.isEnabled = true } }
This Worked For me
This is what worked for me to handle any dismissal such as
searchBar.resignFirstResponder()
,view.endEditing(false)
, interactive swipe to dismiss, presenting a view controller, etc.Making sure to set
searchBar.delegate = self
.Try this simple solution, works perfect for me
You can use the runtime API to access the cancel button.
As far as your question is concerned, there is no way you can enable the cancel button when the keyboard is dismissed, like there is no callback as such.
Implement the below searchBarShouldEndEditing delegate method in your code. Hope it will helpful.