打开键盘时移动菜单 (Swift)

Move menu when the keyboard opens (Swift)

我的功能有问题 "keyboardWillShown"。所以我想要的是我的菜单在打开时恰好出现在键盘上方。它在 Iphone 8 plus, 8, 7, 6 上完美运行。但是当我在模拟器上 运行 Iphone 11 时,结果如下。

Picture of how it looks in Iphone 11

Constrains

这是我的代码:

@objc func keyboardWillShown(notification: NSNotification) {
    let info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    UIView.animate(withDuration: 0.1, animations: { () -> Void in
        self.keyboardConstrains.constant = keyboardFrame.size.height
    })
}

调用函数

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShown(notification:)), name:  UIResponder.keyboardWillShowNotification, object: nil )
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver( self,name:  UIResponder.keyboardWillShowNotification, object: nil )
}

您可以根据自己的屏幕大小设置约束条件

if self.view.height >= 800{ //For bigger screens (X ,11)
    self.keyboardConstrains.constant = keyboardFrame.size.height - 50
} else {
    self.keyboardConstrains.constant = keyboardFrame.size.height
}
let window = UIApplication.shared.keyWindow
let bottomPadding = window?.safeAreaInsets.bottom
keyboardConstrains.constant = (keyboardSize?.height)! - (bottomPadding ?? 0)

这是因为所有槽口 iPhone(X, Xr, iPhone11 etc) 在底部都有安全区域,所以键盘高度是从主视图计算的,你正在设置 "keyboardConstrains" 来自安全区域,这就是 space 即将到来的原因。要删除这个 space 你必须检查底部是否有安全区域,而不是你必须从键盘高度减去底部 space。