I have a search bar with cancel button. But when I click on Cancel button it doesn\'t close the search bar. How can I make that on click on Cancel it will return search bar to t
When you tap the cancel button, the searchBar
sees it like you've got a new thing to search, that's why if you put resignFirstResponder()
on the cancelButton
clicked it won't work, because after this it will call didBeginText
.
So I put a condition in didBeginText
, so when the string in the search has less or 0 characters it will resign the first responder. Just like this:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count < 1 {
searchBar.resignFirstResponder()
}
}
It's an easy approach and works as well. Best regards!