evorg88
evorg88

Reputation: 215

View keeps moving down in iPhoneX on keyboard dimissal

I'm carrying out tests on different devices and have noticed a problem when I come to test on an iPhone X.

Basically, on my view, I have an image, a text-field and a button; all within a stack view that is centred horizontally and vertically. When I tap the text-field and the keyboard presents itself, I move the view upwards so as not to block any content with the keyboard - and vice-versa when the keyboard returns. Here is my code:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height/2
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height/2
        }
    }
}

I have added the observers to viewDidLoad():

NotificationCenter.default.addObserver(self, selector: #selector(nameVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(nameVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

This has worked fine on all device types within the simulator - except for the iPhone X.

As shown by the image below, when the keyboard dismisses on an iPhone X, the view moves downwards. This happens again and again until the text-field is covered by the keyboard and I have to restart the app to regain control.

I am completely stumped with this one, how can this code work on every device type except the iPhone X?

Please can anybody help![enter image description here

Upvotes: 1

Views: 183

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11243

You should use keyboardFrameEndUserInfoKey instead of keyboardFrameBeginUserInfoKey which returns the proper height with safeAreaInsets.

Upvotes: 2

Related Questions