How can I programmatically check whether a keyboard is present in iOS app?
…or take the easy way:
When you enter a textField, it becomes first responder and the keyboard appears. You can check the status of the keyboard with [myTextField isFirstResponder]
. If it returns YES
, then the the keyboard is active.
drawnonward's code is very close, but collides with UIKit's namespace and could be made easier to use.
@interface KeyboardStateListener : NSObject { BOOL _isVisible;}+ (KeyboardStateListener *)sharedInstance;@property (nonatomic, readonly, getter=isVisible) BOOL visible;@endstatic KeyboardStateListener *sharedInstance;@implementation KeyboardStateListener+ (KeyboardStateListener *)sharedInstance{ return sharedInstance;}+ (void)load{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; sharedInstance = [[self alloc] init]; [pool release];}- (BOOL)isVisible{ return _isVisible;}- (void)didShow{ _isVisible = YES;}- (void)didHide{ _isVisible = NO;}- (id)init{ if ((self = [super init])) { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(didShow) name:UIKeyboardDidShowNotification object:nil]; [center addObserver:self selector:@selector(didHide) name:UIKeyboardWillHideNotification object:nil]; } return self;}@end
Create a UIKeyboardListener
when you know the keyboard is not visible, for example by calling [UIKeyboardListener shared]
from applicationDidFinishLaunching
.
@implementation UIKeyboardListener+ (UIKeyboardListener) shared { static UIKeyboardListener sListener; if ( nil == sListener ) sListener = [[UIKeyboardListener alloc] init]; return sListener;}-(id) init { self = [super init]; if ( self ) { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(noticeShowKeyboard:) name:UIKeyboardDidShowNotification object:nil]; [center addObserver:self selector:@selector(noticeHideKeyboard:) name:UIKeyboardWillHideNotification object:nil]; } return self;}-(void) noticeShowKeyboard:(NSNotification *)inNotification { _visible = true;}-(void) noticeHideKeyboard:(NSNotification *)inNotification { _visible = false;}-(BOOL) isVisible { return _visible;}@end