How to detect when the keyboard appears and disappears in iOS

To detect when the keyboard from a UITextField is being brought up (and goes away again), the UITextField Delegate Protocol won’t help us. Instead we need to listen to two notifications, namely UIKeyBoardWillShow and UIKeyboardWillHide.

We could setup the observers in viewDidLoad, like this for example:

- (void)viewDidLoad {
    [super viewDidLoad];
    // setup keyboard observers
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardCameUp:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWentAway:) name:UIKeyboardWillHideNotification object:nil];

These observers will call a method in our class (using @selector). Mine are called keyboardCameUp and keyboardWentAway:

- (void)keyboardCameUp:(NSNotification *)notification {
    NSLog(@"Keyboard came up!");

- (void)keyboardWentAway:(NSNotification *)notification {
    NSLog(@"Keyboard went away!");

The notification can be used to detect some properties of the keyboard, for example its height and width.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.