I am dealing with the problem of moving the view when the keyboard covers an element that just gained the first responder. I started by looking at this question and it gave me a great head start.
After adding the observers to UIKeyboardWillShow
and UIKeyboardWillHide
I ended with the following code:
func keyboardWillShow(notification: Notification) {
guard let userInfo = notification.userInfo,
let kbRect = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double else {
return
}
let kbSize = kbRect.cgRectValue.size
UIView.animate(withDuration: duration) {
self.view.transform = CGAffineTransform(translationX: 0, y: -kbSize.height)
}
}
func keyboardWillHide(notification: Notification) {
UIView.animate(withDuration: 0.3) {
self.view.transform = CGAffineTransform(translationX: 0, y: 0)
}
}
It works fine in the sense that the view moves up and down when a text field gains the first responder. However, when a key is pressed, the view moves again and defeats the purpose of moving it up on the first place. I made a little GIF to better describe this undesired behavior, the first time the keyboard appears and disappears shows the correct behavior, the second time, when a key is pressed, shows the undesired one.
So, the question is, is there a way I could prevent the view movement when a key is pressed? I would like the view to stay "up" when the user is using the keyboard to insert text.