Swift - 在显示时将textField移动到键盘上

时间:2017-11-07 18:39:18

标签: ios swift uiview keyboard

我需要在键盘上显示文本字段。

我使用以下代码:

override func viewDidLoad() {
    super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}

然后:

@objc func keyBoardWillShow(_ notification: NSNotification) {
    let userInfo:NSDictionary = notification.userInfo! as NSDictionary
    let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height

    UIView.animate(withDuration: 0.4) {
        self.commentViewBottomConstraint.constant = keyboardHeight
        self.view.layoutIfNeeded()
    }
}
@objc func keyBoardWillHide(_ notification: NSNotification) {
    UIView.animate(withDuration: 0.4) {
        self.commentViewBottomConstraint.constant = 0
        self.view.layoutIfNeeded()
    }
}

问题是键盘高度似乎不正确。实际上,视图的底部未与键盘对齐。视图和键盘之间有一个空格。

enter image description here

老实说,我不明白我做错了什么......

谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我认为问题在于底部约束是相对于安全区域的。 所以我通过添加它来修复它:

let safeAreaHeight = self.view.safeAreaInsets.bottom
self.commentViewBottomConstraint.constant = keyboardHeight - safeAreaHeight

这里是完整的代码:

 @objc func keyBoardWillShow(_ notification: NSNotification) {
    let userInfo:NSDictionary = notification.userInfo! as NSDictionary
    let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
    let safeAreaHeight = self.view.safeAreaInsets.bottom

    UIView.animate(withDuration: 0.4) {
        self.commentViewBottomConstraint.constant = keyboardHeight - safeAreaHeight
        self.view.layoutIfNeeded()
    }
}