0

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.

problem presented

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.

  • how did you set up this image? what are constraints there? – Lu_ Oct 17 '17 at 18:41
  • @Lu_ it happens to me on every view, that image i just a test UIView I did to illustrate the problem am having. The constraints on the image are just top, leading and trailing to superview, one to textfield at bottom, all with 8 as value – Rodrigo Ruiz Murguía Oct 17 '17 at 18:58

2 Answers2

0

You should move view app, not transform it, use:

self.view.frame.origin.y -= kbSize.height

transforming should behave like it is right now

Lu_
  • 2,577
  • 16
  • 24
0

Set your UIView as a Outlet and insert this code in viewDidLoad

yourView.translatesAutoresizingMaskIntoConstraints = true
AndreiVataselu
  • 216
  • 2
  • 16