skip to Main Content

I am setting up my keyboard will show notifier, getting the keyboard height, and setting the constant value on the bottom constraint as shown here:

Notification Observer

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)

Keyboard Will Show Function

@objc func keyboardWillShow(notification: NSNotification) {
    guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
        return
    }

    _keyboardHeight = keyboardFrame.cgRectValue.height
    changeStateContainerBottomConstraint.constant = _keyboardHeight
}

However on newer models of phones the value I am getting back is placing the view higher than the top of the keyboard as shown in the screenshots below. I am hesitant to adjust the constraint with a static value as that could change in the future, or from model to model. Has anyone else come across this issue and have a solution?

iPhone SE Screenshot
enter image description here

iPhone 14 Pro Screenshot
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    It looks like I've found a workable solution. Just needed to find the bottom value of the safe area insets and subtract it from the returned height. Here is what keyboardWillShow looks like now

     @objc func keyboardWillShow(notification: NSNotification) {
        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }
    
        _keyboardHeight = keyboardFrame.cgRectValue.height
        let bottom: CGFloat = UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0
        changeStateContainerBottomConstraint.constant = _keyboardHeight - bottom
    }
    

  2. I would suggest you look at this framework https://github.com/hackiftekhar/IQKeyboardManager which is the most popular library to handle this kind of stuff. It’s easier to use with a few lines of code like IQKeyboardManager.shared.enable = true in your AppDelegate file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search