iPhone X键盘通知高度不同

时间:2018-12-25 03:11:38

标签: ios iphone swift uitableview uitextfield

最近我一直在使用keyboardWillShowkeyboardWillShow时发生这种奇怪的情况,其中从(notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue获取键盘高度的初始调用返回的值为477px然后所有其他时间之后,该值现在为535px,即大了58px。但是,从外观上看,键盘的外观没有任何改变。两个键盘都启用了预测栏。

作为背景信息,需要键盘高度的目的是抵消一个表格视图的滚动,在该表格视图中每个单元格都包含一个文本字段,并且我正在比较该文本字段的位置,以查看编辑开始时是否隐藏在键盘后面

我在理解这种方法的方式上是否缺少某些东西?

2 个答案:

答案 0 :(得分:1)

这对您有帮助吗?

 NotificationCenter.default.addObserver(self, selector: #selector(CommentsVC.keyboardWillShow), name: 
 NSNotification.Name.UIKeyboardWillShow, object: nil)
                    NotificationCenter.default.addObserver(self, selector: #selector(CommentsVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

@objc func keyboardWillHide(_ notification: NSNotification) {
                UIView.animate(withDuration: 0.3) {
                    self.inputContainerViewBottom.constant = 0


                    self.view.layoutIfNeeded()


                }
            }


@objc func keyboardWillShow(_ notification: NSNotification) {
                print(notification)
                let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
                UIView.animate(withDuration: 0.3) {
                    self.inputContainerViewBottom.constant = keyboardFrame!.height

                    self.view.layoutIfNeeded()


                    let flag = self.tableComments.isCellVisible(section: 0, row: 10 - 1)

                    if flag
                    {
                        self.scrollToBottom()
                    }
                    else
                    {

                    }

                }
            }

注意:inputContainerViewBottom是底部约束的出口

答案 1 :(得分:1)

我只是面临类似的情况,解决方案基本上是这样:

func keyboardWillShow(_ notification: Notification) {
    guard
        let userInfo = notification.userInfo,
        let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
        let keyboardEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
    else { return }

    let window = UIApplication.shared.keyWindow
    let bottomPadding = window?.safeAreaInsets.bottom ?? 0.0 // This is the key
    buttonConstraint.constant = keyboardEndFrame.height - bottomPadding
    UIView.animate(withDuration: animationDuration) { [weak self] in
        self?.view.layoutIfNeeded()
    }
}

iPhone X(以及其他带有OLED的设备)具有safeAreaInsets,您的情况下会添加它。