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 rem
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.
}
}
}