Search code examples
iosswiftiphonexcodekeyboard

Move menu when the keyboard opens (Swift)


I have problems with my function "keyboardWillShown". So what I want is that my menu appears exactly above the keyboard when it opens. It works perfectly on Iphone 8 plus, 8, 7, 6. But when I run Iphone 11 on the simulator the result is as follows.

Picture of how it looks in Iphone 11

Constrains

Here's my code:

@objc func keyboardWillShown(notification: NSNotification) {
    let info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    UIView.animate(withDuration: 0.1, animations: { () -> Void in
        self.keyboardConstrains.constant = keyboardFrame.size.height
    })
}

Calling function

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShown(notification:)), name:  UIResponder.keyboardWillShowNotification, object: nil )
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver( self,name:  UIResponder.keyboardWillShowNotification, object: nil )
}

Solution

  • you can set the constraints according to the size of your screen

    if self.view.height >= 800{ //For bigger screens (X ,11)
        self.keyboardConstrains.constant = keyboardFrame.size.height - 50
    } else {
        self.keyboardConstrains.constant = keyboardFrame.size.height
    }