@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正在测试时。我可以看到它将键盘计算为零。此外,当我连接硬件键盘并将其删除时,我可以在代码中看到键盘高度为零。
这是苹果框架的错误吗?
答案 0 :(得分:1)
通知仅显示屏幕上显示的键盘高度。
当硬件键盘连接到设备时,键盘不需要显示在屏幕上,因此键盘的键盘高度将为零
我会使用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)")
}