出现时键盘高度会有所不同

Gav*_*vin 3 nsnotifications ios swift

我试图通过将底部约束修改为键盘高度来显示键盘时的视图。但是返回给我的键盘高度是变化的。

当我点击模拟器中的文本字段时,键盘高度为302。当我尝试打开和关闭软件键盘时,它显示260何时出现键盘。为什么会这样呢?

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FriendsViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)

func keyboardWillShow(notification: NSNotification) {
    print("Keyboard appearing")
    guard let keyboardHeight = (notification.userInfo! as NSDictionary).objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size.height else {
        return
    }
    bottomConstraint.constant = keyboardHeight
    print("keyboard height : \(keyboardHeight)")
    self.view.layoutIfNeeded()
}
Run Code Online (Sandbox Code Playgroud)

的高度260实际上是正确的高度,因为它完美地调整了我的视野。随着302我的观点高度偏移了太多。

我的观点的布局是。UITextField在顶部,然后在其UITableView下方。

dah*_*boy 10

马特(Matt)的修改答案,并附有理由

他是对的,您需要使用UIKeyboardFrameEndUserInfoKey而不是UIKeyboardFrameBeginUserInfoKey因为

  1. UIKeyboardFrameEndUserInfoKey 根据您在设置中设置的偏好来给您最终的身高。

  2. UIKeyboardFrameEndUserInfoKey返回两次的身高,第一个是没有语言预测的,如您在键盘上方所见,第二个是带谓词的(如果已从设置中激活,但UIKeyboardFrameBeginUserInfoKey没有预测条则返回)。

开启高度 iPhone 5s

在此处输入图片说明


mat*_*att 7

问题是你正在看UIKeyboardFrameBeginUserInfoKey。你想看的是UIKeyboardFrameEndUserInfoKey