Dismissing keyboard from UISearchBar when the X button is tapped

前端 未结 14 1214
眼角桃花
眼角桃花 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:42

    Updated for SWIFT 3:

    Suppose that the user has entered a string in searchfield and clicks x the following code works to hide keyboard when x is pressed

    `

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 
    {
                if searchBar.text == nil || searchBar.text == ""
                {
                    searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1)
                }
     }
    

    `

提交回复
热议问题