Marco
Marco

Reputation: 1061

Swift - move textField over keyboard upon showing

I need to move a textfield over the keyboard when it appears.

I am using the following code:

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

and then:

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

the problem is that it seems the keyboard height is not correct. In fact the bottom of the view is not aligned with the keyboard. There is a space between the view and the keyboard.

enter image description here

Honestly i don't understand what I am doing wrong...

Thank you for the help!

Upvotes: 1

Views: 241

Answers (1)

Marco
Marco

Reputation: 1061

I think the problem was the fact the bottom constraint was relative to the safe area. So I have fixed it by adding this:

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

Here's the complete code:

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

Upvotes: 1

Related Questions