我使用UISearchBar来过滤表视图的数据,并且我希望在搜索栏没有查询文本时关闭键盘(通过点按键盘上的删除按钮或点按搜索栏上的清除按钮来删除文本)。根据我从stackoverflow上其他文章中学到的信息,我知道即使您在textDidChange UISearchBarDelegate方法中调用searchBar.resignFirstResponder(),单击搜索栏清除按钮(带有x图标的灰色圆形按钮)也将显示键盘。因此,如果单击搜索栏清除按钮,键盘将被隐藏,然后再次闪回,而手动删除文本将隐藏键盘。
唯一的解决方案是在DispatchQueue.main.async代码块内调用resignFirstResponder()方法。
有人可以解释为什么您必须在主队列上异步调用resignFirstResponder()方法来关闭键盘吗?为什么直接调用它不起作用?
检查下面的代码:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text?.count == 0 {
loadItems()
//the following code works!
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
// //this line of code only works when you tap the deleting keyboard button to remove the query text
// //does not work if you click the searchbar clear button
// searchBar.resignFirstResponder()
}
}
textDidChange
委托方法退出。这就是异步重新进入主线程所做的事情。