Yasser B. Yasser B. - 2 years ago 260
Swift Question

Keyboard height change observer swift iOS

How to detect Keyboard height change, or keyboard change in iOS swift.

I'm able to add an observer for my app to detect wether the Keyboard is show or not using :

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentView.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentView.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)

and I'm changing my button position according to that :

func keyboardWillShow(notification: NSNotification) {

func keyboardWillHide(notification: NSNotification) {

func animateTextFieldWithKeyboard(notification: NSNotification) {

let userInfo = notification.userInfo!

let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt

// baseContraint is your Auto Layout constraint that pins the
// text view to the bottom of the superview.

if notification.name == UIKeyboardWillShowNotification {
if (BottomConstraint.constant == 0) {
BottomConstraint.constant += keyboardSize.height

// move up
else {
BottomConstraint.constant = 0
// move down


let options = UIViewAnimationOptions(rawValue: curve << 16)
UIView.animateWithDuration(duration, delay: 0, options: options,
animations: {
completion: nil


Everything is working fine as you can see in the screenshot :

enter image description here

But the problem comes when I change the keyboard type to Emoji for example. it hides my textField and my Button, so I would like to change the position of the button and the TextFiend according to the keyboard new height

enter image description here

Answer Source

If you search on UIKeyboardWillShowNotification in the Xcode docs you get to the section on UIWindow, which has a table of notifications at the end.

I suggest trying the UIKeyboardWillChangeFrameNotification.

Time to find the answer: About 30 seconds.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download