Giacomo Dughiero
Giacomo Dughiero

Reputation: 5

Updating constraints of text field based on keyboard height

Sorry if this doesn't look good, but I'm at my first attempts with programming and still learning. This is my code:

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

In my console output I get that heighOfKeyboard is still 0.0 and I think it's because the method textFieldDidBeginEditing gets triggered before keyboardWillShow. How do I make the heightOfKeyboard take the value of keyboardHeight before textFieldDidBeginEditing gets triggered?

Thank you for your answers!!

Upvotes: 0

Views: 40

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can put all stuff in 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()
                }

            }

        }

Upvotes: 1

Related Questions