I\'m using the UISearchBar (but not the SearchDisplayController that\'s typically used in conjunction) and I\'d like to dismiss the keyboard when you hit the \'X\' button.>
When you click the 'x' button, the string in the search bar text field becomes an empty collection of characters.
Checking the length of the collection helps to detect when the 'x' button has been clicked.
I had a similar issue and this solution worked for me:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//let searchText = searchText.trimmingCharacters(in: .whitespaces)
if searchText.isEmpty{
DispatchQueue.main.async { [weak self] in
guard let self = self else{ return }
self.searchBar.resignFirstResponder()
}
}
}