为什么计算键盘尺寸有时会产生零高度

Why does Calculating keyboard size sometimes produces a zero height

@objc private func keyboardWasShown(aNotification: NSNotification) {

        if let info = aNotification.userInfo as? [String: AnyObject] {
            if let keyboardFrame = info[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
                let kbSize = keyboardFrame.cgRectValue.size
                containerViewBottomConstraint?.constant = -kbSize.height
                weak var weakSelf = self
                UIView.animate(withDuration: 0.4) {
                    weakSelf?.layoutIfNeeded()
                }
            }
        }
    }

我尝试了 UIKeyboardDidShow 和 UIKeyboardDidShow 通知。

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(aNotification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)


NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(aNotification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)

这种情况很少发生,而且只有在 qa 进行测试时才会发生。我可以看到它将键盘计算为零。此外,当我连接了硬件键盘并将其移除时,我可以在代码中看到键盘高度为零。

这是苹果框架的错误吗?

硬件键盘:

  • 通知仅指示屏幕上显示的键盘高度。

  • 当硬件键盘连接到设备时,键盘不需要显示在屏幕上,因此键盘高度将为零

键盘高度:

我会使用 UIKeyboardDidShow 通知和 UIKeyboardFrameEndUserInfoKey 获取键盘框架(以及随后的高度)

@objc private func keyboardWasShown(notification: NSNotification) {
    
    guard let userInfo = notification.userInfo,
        let endFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
            return
    }

    let keyboardHeight = endFrame.height
    
    print("keyboardHeight = \(keyboardHeight)")
}