Search code examples
iosswiftiphone-x

iPhone X keyboard appear showing extra space


I have created a chat UI in which I have added a constraint for the tableView to the bottom of the screen. I am changing the constraint value by adding the height of the keyboard which is working fine in all the devices except iPhone X.

UI when key board is not visible:

enter image description here

Which is fine.

Problem is when keyboard appears blank space is visible in between the textView and the keyboard:

enter image description here

Do I have to try for a different approach for this or it can be resolved using constraints ?


Solution

  • Try subtracting the height of the safe area's bottom inset when calculating the value for your constraint.

    Here is a sample implementation which handles a UIKeyboardWillChangeFrame notification.

    @objc private func keyboardWillChange(_ notification: Notification) {
        guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
        let newHeight: CGFloat
        if #available(iOS 11.0, *) {
            newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
        } else {
            newHeight = value.cgRectValue.height
        }
        myConstraint.value = newHeight
    }