Getting the keyboard height

Some time ago I answered a question in StackOverflow comparing the keyboard height on the iPhone X and the iPhone 8:

I got these heights by:
1. Adding an observer of the UIResponder.keyboardWillShowNotification notification:

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

(In fact, if we want all keyboard frame changes, we should probably be observing the keyboardWillChangeFrameNotification notification, I discuss this in my book.)

2. Adding the selector function to be called:

@objc func keyboardWillShow(_ notification: NSNotification) {
}

3. Then, within this function, we need to dig down a crazy chain of downcasts and optional unwrapping from the userInfo dictionary to extract the height out of the notification object:

if let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
      print(keyboardRect.height)
}

Done! We have the keyboard height.

The person I was answering on StackOverflow was trying to display a view directly above the keyboard, and was confused about why it wasn’t displaying in the correct place. (I believe there was some confusion because of the safe area inset on the iPhone X.)

To illustrate that displaying the view was possible, I set up a red rectangle directly above the keyboard. I was recently asked on Twitter how I did this:

Well, pretty straightforward, actually. Now we have the keyboardRect, all I had to do was set up a CGRect just above it, convert that to a CAShapeLayer, give it a strokeColor and lineWidth, and add it to the view’s layer.

      let newRect = CGRect(x: 0, y: view.frame.height - keyboardRect.height - 100, width: keyboardRect.width, height: 100)
      let rectLayer = CAShapeLayer()
      rectLayer.path = CGPath(rect: newRect, transform: nil)
      rectLayer.strokeColor = UIColor.red.cgColor
      rectLayer.lineWidth = 5
      view.layer.addSublayer(rectLayer)

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with:
Posted in Swift

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: