Dismissing keyboard from UISearchBar when the X button is tapped

前端 未结 14 1243
眼角桃花
眼角桃花 2020-12-24 07:42

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.

14条回答
  •  天命终不由人
    2020-12-24 08:37

    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()
            }
        }
    }
    

提交回复
热议问题