ios - 在不影响取消按钮的情况下关闭 UISearchBar 键盘

标签 ios swift uisearchbar uikeyboard

我正在尝试重现可以在 iphone 上的联系人应用程序中看到的功能。我有一个 UISearchBar,它在单击搜索按钮时关闭键盘。然而,这会停用取消按钮,并且需要触摸 2 次才能激活。在联系人应用程序上,当点击搜索按钮并关闭键盘时,它不会被停用。

所以我想问的是如何在不禁用 uiSearchBar 上的取消按钮的情况下关闭键盘?

我试过了

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

//Some other code

//I have Tried
//Attempt 1
 self.searchBar.endEditing(true)
//Attempt 2
  self.searchBar.resignFirstResponder()
//Attempt 3
  var textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField
  textFieldInsideSearchBar.endEditing(true)

    }

最佳答案

委托(delegate)方法解析您的 searchBar,因此您不必使用 self.searchBar,这可能是问题之一。我通常使用您的“尝试 2” 中的逻辑。

你可以尝试实现这个:

func searchBarTextDidEndEditing(_ searchBar: UISearchBar)

并调用 searchBar.resignFirstResponder()

如果不行,那就尝试实现这个方法,返回true:

func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool

如果您将 UISearchBar 与 UISearchDisplatController 结合使用,请在 searchDisplayController 上尝试此方法:

func setActive(_ visible: Bool, animated animated;: Bool)

关于ios - 在不影响取消按钮的情况下关闭 UISearchBar 键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32165520/

相关文章:

ios - 自定义 UITableViewCell 导致 UISearchBar 崩溃

iphone - 如何更改 iphone 中 UISearchBar 的 UiSearchbar 高度、宽度、颜色和 Uitextfield 高度?

xcode - 你如何改变发展目标?

ios - NSDateFormatter dateFromString 返回错误的日期

ios - Xcode 8每次都重新编译完整代码

ios - 如何在 UITableViewCell 中使用 UIAlertController

ios - UIViewController 状态栏顶部插图

swift - iOS 12 wkwebview 无法使用重定向?

iphone - UISearchBar - 范围栏动画

ios - 在其他 View iOS 中停止 AvAudioPlayer