get keyboard height in swift

To get the height of the keyboard in iOS, you can use the UIResponder.keyboardFrameEndUserInfoKey key to access the frame of the keyboard when it appears. Here's an example of how you can do this:

main.swift
@objc func keyboardWillShow(_ notification: Notification) {
    guard let userInfo = notification.userInfo else { return }
    let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
    let keyboardHeight = keyboardFrame?.height ?? 0
    // Use the keyboard height in your code
}

// Add observer for the keyboard will show notification
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
512 chars
10 lines

In this example, we're adding an observer for the UIResponder.keyboardWillShowNotification notification, which is triggered when the keyboard is about to appear. When this notification is received, we're accessing the keyboardFrameEndUserInfoKey value from the userInfo dictionary, which contains the frame of the keyboard when it appears. We're then getting the height of the keyboard from this frame, and using it in our code.

gistlibby LogSnag