Keyboard and getting up state on iPhone
How do I find out if the keyboard is up?
I have a UISearchbar instance which becomes the first responder.
When the keyboard appears a notification is sent out as part of the API, however I don't want t开发者_JAVA技巧o respond to this right away. I could record this in a boolean state, but that seems clunky. I'd like to know if there is a "getter" some where I can call to find out.
This is how I do it:
KeyboardStateListener.h
@interface KeyboardStateListener : NSObject {
BOOL _isVisible;
}
+ (KeyboardStateListener *) sharedInstance;
@property (nonatomic, readonly, getter=isVisible) BOOL visible;
@end
KeyboardStateListener.m
#import "KeyboardStateListener.h"
static KeyboardStateListener *sharedObj;
@implementation KeyboardStateListener
+ (KeyboardStateListener *)sharedInstance
{
return sharedObj;
}
+ (void)load
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
sharedObj = [[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;
}
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
@end
Then use this to figure out the rest:
KeyboardStateListener *obj = [KeyboardStateListener sharedInstance];
if ([obj isVisible]) {
//Keyboard is up
}
The only sure way that I can think to do it as you said. using notifications like this:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
and then
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
Other than that, you may be able to iterate through your views subviews and look for the keyboard like:
UIView *keyboard = nil;
for (UIView *potentialKeyboard in [myWindow subviews]) {
// iOS 4
if ([[potentialKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
potentialKeyboard = [[potentialKeyboard subviews] objectAtIndex:0];
}
if ([[potentialKeyboard description] hasPrefix:@"<UIKeyboard"]) {
keyboard = potentialKeyboard;
break;
}
}
But I am not sure if this will break when the SDK changes ...
Maybe use this method and add a category to the window so that you can just always ask the window for the keyboard ... just a thought.
精彩评论