如何判断键盘是否已启动?
我有一个UISearchbar实例,它成为第一个响应者。
当键盘出现时,通知会作为API的一部分发出,但我不想立即回复。我可以将它记录在一个布尔状态,但这似乎很笨拙。我想知道是否有一个“吸气剂”,我可以打电话找出来。
答案 0 :(得分:3)
我就是这样做的:
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
然后用它来弄清楚其余部分:
KeyboardStateListener *obj = [KeyboardStateListener sharedInstance];
if ([obj isVisible]) {
//Keyboard is up
}
答案 1 :(得分:2)
我能想到的唯一可靠的方法就像你说的那样。使用这样的通知:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
然后
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
除此之外,您可以遍历视图子视图并查找键盘,如:
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;
}
}
但我不确定当SDK更改时这是否会中断...
也许使用这种方法并在窗口中添加一个类别,这样你就可以随时向窗口询问键盘......只是想一想。