Steve Barden
Steve Barden

Reputation: 644

How to get keyboard height WITHOUT relying on notifications

I know how to set up an NSNotification observer to detect when the keyboard shows/hides. From this I can get the height of the keyboard. But what happens if the device is rotated while the keyboard is still showing?

Is there a way to get the height of the keyboard in this new state? Since the keyboard is still showing a new notification will not be triggered.

Upvotes: 15

Views: 11764

Answers (2)

Marcus Adams
Marcus Adams

Reputation: 53830

On iOS 6+, if you've registered to receive the UIKeyboardDidShowNotification, your selector will be called called again when the orientation changes.

This is the notification that Apple uses in their sample code for Managing the Keyboard, however, when using this notification, their calculation is wrong when calculating the keyboard height in landscape mode:

CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

Replace the above with this:

// Works in both portrait and landscape mode
CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
kbRect = [self.view convertRect:kbRect toView:nil];

CGSize kbSize = kbRect.size;

Upvotes: 5

Mick MacCallum
Mick MacCallum

Reputation: 130193

You still have to use NSNotificationCenter, but you have to observe a different key. The key you're looking for is UIKeyboardDidChangeFrameNotification which according to the docs is posted immediately after a change in the keyboard’s frame.

Upvotes: 13

Related Questions