I'm trying to move the constraintToBottom.constant
of a UIView
where my UITextField
is located above the keyboard once it's shown. I set the Notification
observer, but for some reason it's not working.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
UIView.animate(withDuration: 0.3, animations: {
self.constraintToBottom.constant = keyboardSize.height
print("constant", self.constraintToBottom.constant)
})
}
}
When I print the constraintToBottom.constant
it shows:
constant 346.0
And yet, the UIView
is still not visible above the keyboard as usual. What am I doing wrong?
UPDATE
As suggested, the minus does the trick BUT there's also extra space and it looks like this:
You need to re-layout the view
self.constraintToBottom.constant = -1 * keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
print("constant", self.constraintToBottom.constant)
})