基于键盘高度更新文本字段的约束

时间:2018-02-23 16:34:19

标签: ios swift keyboard constraints textfield

很抱歉,如果这看起来并不好看,但是我第一次尝试编程并且还在学习。 这是我的代码:

        func textFieldDidBeginEditing(_ textField: UITextField) {
    var heightOfKeyboard = CGFloat(0.0)
    UIView.animate(withDuration: 0.5) {

        func keyboardWillShow(_ notification: Notification) {
            if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
                let keyboardRectangle = keyboardFrame.cgRectValue
                let keyboardHeight = keyboardRectangle.height
                heightOfKeyboard = keyboardHeight
            }

        }
        print(heightOfKeyboard)
        self.heightConstraint.constant = heightOfKeyboard + CGFloat(50)
        self.view.layoutIfNeeded()
    }
}

在我的控制台输出中,我得知heighOfKeyboard仍为0.0,我认为这是因为textFieldDidBeginEditing方法在keyboardWillShow之前被触发。在textFieldDidBeginEditing被触发之前,如何使heightOfKeyboard获取keyboardHeight的值?

感谢您的回答!!

1 个答案:

答案 0 :(得分:1)

您可以将所有内容放入show

func keyboardWillShow(_ notification: Notification) {

                if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
                let keyboardRectangle = keyboardFrame.cgRectValue
                let keyboardHeight = keyboardRectangle.height
                print(keyboardHeight )
                self.heightConstraint.constant = keyboardHeight + CGFloat(50)

                 UIView.animate(withDuration: 0.5) {            

                    self.view.layoutIfNeeded()
                }

            }

        }