UISearchbar clearButton forces the keyboard to appear

Viewed 41318

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.

12 Answers

Pressing the "clear" button in a UISearchBar automatically opens the keyboard even if you call searchBar.resignFirstResponder() within the textDidChange UISearchBarDelegate method.

To actually hide the keyboard when you press the "x" to clear the UISearchBar, use the following code. This way, even if textDidChange gets called while typing something in the UISearchBar, you only hide the keyboard if you delete all the text within it, weather you use the delete button or you click the "x":

extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text!.count == 0 {
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        } else {
            // Code to make a request here.
        }
    }
}

A Swift version of @boliva 's answer.

class MySearchContentController: UISearchBarDelegate {

    private var searchBarShouldBeginEditing = true

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchBarShouldBeginEditing = searchBar.isFirstResponder
    }

    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        defer {
            searchBarShouldBeginEditing = true
        }
        return searchBarShouldBeginEditing
    }
}

In your endEditing method, why don't you clear the UISearchBar and there? Since that must be where you resign first responder also, it makes sense.

Of of the search bar delegate calls asks you to accept a change from an old value to a new one - you could detect that the new value was nil, along with the old value being not-nil, and an indicator that the user had not typed anything since the keyboard was last up - then in that case resign first responder for the search bar. Not sure if the keyboard will momentarily display though.

I have a very similar situation and may try that myself.

Related