【问题标题】:Swift - move textField over keyboard upon showingSwift - 在显示时将文本字段移动到键盘上
【发布时间】:2018-04-20 06:49:29
【问题描述】:

当它出现时,我需要在键盘上移动一个文本字段。

我正在使用以下代码:

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()
    }
}

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

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

感谢您的帮助!

【问题讨论】:

    标签: ios swift uiview keyboard


    【解决方案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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-20
      • 1970-01-01
      • 2016-06-11
      • 2015-05-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      相关资源
      最近更新 更多