Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get actual keyboard height (keyboard height minus safe area insets)

Tags:

ios

swift

I tried getting the height of the keyboard to update the table contentInsets when the keyboard shows up; but the notification from UIResponder.keyboardWillShowNotification shows the frame with the safe area height. Is there a way to get the actual keyboard frame?

Code for the height of the keyboard height:

if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height

    print("show: \(keyboardHeight)")
    tableView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 18 + keyboardHeight, right: 0)
    tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 18 + keyboardHeight, right: 0)
}

But this gives the height of the following keyboard: https://i.sstatic.net/Y3uqk.jpg

What I want: https://i.sstatic.net/3xUbW.jpg

like image 262
Devxln Avatar asked Oct 27 '25 08:10

Devxln


2 Answers

First you have to get Safe Area bottom height and then exclude it from keyboard total height. In this way you will get only keyboard height without bottom safe area.

pesudo code:

let keyboardHeight = your keyboard height - bottomPadding

if #available(iOS 11.0, *) {
    let window = UIApplication.shared.keyWindow
    let bottomPadding = window?.safeAreaInsets.bottom
}

Hope it will help you.

like image 141
Muhammad Waqas Bhati Avatar answered Oct 28 '25 22:10

Muhammad Waqas Bhati


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
}
like image 35
Kishan Suthar Avatar answered Oct 28 '25 23:10

Kishan Suthar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!