Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save acoomans/5104704 to your computer and use it in GitHub Desktop.
Save acoomans/5104704 to your computer and use it in GitHub Desktop.
Register UIViewController to listen to keyboard notifications
//
// UIViewController+KeyboardNotifications.h
//
//
// Created by Arnaud Coomans on 15/02/13.
// Copyright (c) 2013 Arnaud Coomans. All rights reserved.
//
#import <UIKit/UIKit.h>
/* With this category, you can use:
#pragma mark - keyboard notifications
- (void)keyboardWillShowNotification:(NSNotification*)notification {}
- (void)keyboardDidShowNotification:(NSNotification*)notification {}
- (void)keyboardWillHideNotification:(NSNotification*)notification {}
- (void)keyboardDidHideNotification:(NSNotification*)notification {}
*/
@interface UIViewController (KeyboardNotifications)
- (void)registerForKeyboardNotifications;
- (void)unregisterForKeyboardNotifications;
@end
//
// UIViewController+KeyboardNotifications.m
//
//
// Created by Arnaud Coomans on 15/02/13.
// Copyright (c) 2013 Arnaud Coomans. All rights reserved.
//
#import "UIViewController+KeyboardNotifications.h"
@implementation UIViewController (KeyboardNotifications)
- (void)registerForKeyboardNotifications {
if ([self respondsToSelector:@selector(keyboardWillShowNotification:)]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
}
if ([self respondsToSelector:@selector(keyboardDidShowNotification:)]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowNotification:) name:UIKeyboardDidShowNotification object:nil];
}
if ([self respondsToSelector:@selector(keyboardWillHideNotification:)]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}
if ([self respondsToSelector:@selector(keyboardDidHideNotification:)]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideNotification:) name:UIKeyboardDidHideNotification object:nil];
}
}
- (void)unregisterForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment