UISearchbar clearButton forces the keyboard to appear

后端 未结 12 1942
暖寄归人
暖寄归人 2020-11-30 20:40

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

12条回答
  •  青春惊慌失措
    2020-11-30 21:27

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

提交回复
热议问题