How to exit from the search on clicking on Cancel button?

前端 未结 10 1158
谎友^
谎友^ 2021-02-07 01:22

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

10条回答
  •  独厮守ぢ
    2021-02-07 01:26

    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!

提交回复
热议问题