首页 > 解决方案 > 当 AccessoryInputView 的键盘不存在时,键盘将显示调用的通知

问题描述

我有一个名为 chatBoxView 的输入附件视图,其中包含一个自定义的 growTextView 和几个用于发送消息的按钮。这个 inputAccessoryView 是在我的主视图控制器中设置的。

 override var inputAccessoryView: UIView? {
     get {
        return chatBoxView
     }
  }
    
 override var canBecomeFirstResponder: Bool {
      return true
  }
    

所以每次我去这个viewController,我都会在屏幕底部看到chatBoxView,这是我想要的。但是,键盘尚不可见(只有 chatBoxView),但为什么我的 KeyBoardWillShow 通知不断被调用?

此外,当键盘打开时,当我点击外部时消失,KeyboardWillDisappear 函数被调用,但 KeyBoardWillShow 函数被调用。

这是键盘通知的功能。

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

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
    @objc func keyboardWillShow(notification: Notification) {
        if let keyboardHeight = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {
            print("Notification: Keyboard will show")
            DispatchQueue.main.async {
                self.tableView.setBottomInset(to: keyboardHeight - self.chatBoxView.frame.height)
                self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true)
            }

        }
    }
    @objc func keyboardWillHide(notification: Notification) {
        print("Notification: Keyboard will hide")
        tableView.setBottomInset(to: 0.0)
    }

所以基本上,当键盘没有显示并且只有附件视图时,我得到了日志“通知:键盘将显示”。有任何想法吗?

标签: iosswiftuirespondernotificationcenterinputaccessoryview

解决方案


问题是您在UIResponder.keyboardFrameEndUserInfoKey. 仅仅看键盘的高度是不够的。您需要查看键盘的位置——查看其整个帧信息。如果键盘的顶部不会高于屏幕底部,显然你不应该做任何事情。同样,如果键盘框架不会从原来的位置改变,你不应该做任何事情。


推荐阅读