Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you keep the cancel button in the search bar enabled when the keyboard is dismissed?

Tags:

enter image description hereenter image description here

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].

like image 874
Pwner Avatar asked Jun 05 '14 23:06

Pwner


2 Answers

Call to [self.searchBar resignFirstResponder] will make the cancel button disabled. Hence, you should always update cancel button to enable after calling it.

Objective-C

[searchBar resignFirstResponder];
UIButton *cancelButton = (UIButton *)[searchBar valueForKey:@"cancelButton"];
[cancelButton setEnabled:YES];

Swift

searchBar.resignFirstResponder()
if let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.isEnabled = true
}

In my experience, view.endEditing(true) is the problem. Because it's also called .resignFirstResponder if there's a UITextField inside the view, which is contained in UISearchBar.

https://developer.apple.com/reference/uikit/uiview/1619630-endediting

like image 92
Seto Avatar answered Sep 20 '22 21:09

Seto


For Swift 4.0

if let cancelButton : UIButton = searchBar.value(forKey: "cancelButton") as? UIButton{
    cancelButton.isEnabled = true
}
like image 35
Muzahid Avatar answered Sep 20 '22 21:09

Muzahid