Search code examples
iosswiftautolayoutnotificationcenter

iOS adjusting bottom constraint constant of view when keyboard visible has a larger offset on newer model iPhones


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


Solution

  • 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
    }