【问题标题】:Updating constraints of text field based on keyboard height基于键盘高度更新文本字段的约束
【发布时间】:2018-02-23 16:34:19
【问题描述】:

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

        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 的值?

感谢您的回答!!

【问题讨论】:

    标签: ios swift keyboard constraints textfield


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

    【讨论】:

    • 谢谢!我需要弄清楚如何处理通知,但我会尽力而为!!
    猜你喜欢
    • 2018-06-15
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多