【问题标题】:On hiding keyboard after edit , UISearchbar hides itself?在编辑后隐藏键盘时,UISearchbar 会隐藏自己吗?
【发布时间】:2019-07-12 22:23:58
【问题描述】:

我使用导航控制器呈现了一个屏幕,在该屏幕中我有一个搜索栏,我在 viewWillAppear() 中将其作为第一响应者。问题是我想在单击完成按钮或单击 searchBar 中的取消时隐藏键盘。但是在对 resignFirstResponder() 和 searchBar.endEditing(true) 做同样的事情时,它也会隐藏 UISearchBar。我也想在状态不处于编辑状态时显示 UISearchBar。

基本上我所做的就是让我的 UISearchBar 成为我的第一响应者:

override func viewWillAppear(_ animated: Bool) {
    searchBar.becomeFirstResponder()
}

然后当用户点击我所做的搜索时:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    // Remove focus from the search bar.
}

取消按钮也是如此。但在我的情况下,这不仅仅是关闭键盘,而是在调用上述函数后隐藏 UISearchbar()。

【问题讨论】:

  • 提供更多细节和代码。
  • @AbuUlHassan 添加了。

标签: ios swift uisearchbar first-responder resignfirstresponder


【解决方案1】:

使用 NotificationCenter addObserver 获取键盘显示和键盘隐藏事件

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// MARK: - Keyboard Hide/Show Functions
@objc func keyboardWillShowNotification(notification: Notification) {
    print("Keyboaed Show")
}

@objc func keyboardWillHideNotification(notification: Notification) {
    print("Keyboaed Hide")
}

注意:-UIviewContoller 消失时不要忘记移除观察者。

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

【讨论】:

  • 我的问题不在于键盘隐藏,而在于 uisearchbar 隐藏了它。
  • 你看过这篇文章了吗? stackoverflow.com/questions/29925373/…
  • 您是否已将委托分配给 UIsearchbar?这可能会导致问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 2019-06-08
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多