给你AppDelegate
一个keyboardFrame
财产。进行适当的AppDelegate
观察UIKeyboardWillShowNotification
和UIKeyboardWillHideNotification
更新属性。将属性设置CGRectNull
为隐藏键盘时,或添加单独的keyboardIsShowing
属性。(您可以测试CGRectNull
使用该CGRectIsNull
功能。)
然后任何对象都可以使用这个咒语随时检查键盘框架:
[[UIApplication sharedApplication].delegate keyboardFrame]
如果您不想将其放入您的应用程序委托中,您可以创建一个单独的单例类,例如
@interface KeyboardProxy
+ (KeyboardProxy *)sharedProxy;
@property (nonatomic, readonly) CGRect frame;
@property (nonatomic, readonly) BOOL visible;
@end
@implementation KeyboardProxy
#pragma mark - Public API
+ (KeyboardProxy *)sharedProxy {
static dispatch_once_t once;
static KeyboardProxy *theProxy;
dispatch_once(&once, ^{
theProxy = [[self alloc] init];
});
return theProxy;
}
@synthesize frame = _frame;
- (BOOL)visible {
return CGRectIsNull(self.frame);
}
#pragma mark - Implementation details
- (id)init {
if (self = [super init]) {
_frame = CGRectNull;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
return self;
}
- (void)keyboardWillShow:(NSNotification *)note {
_frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
- (void)keyboardWillHide:(NSNotification *)note {
_frame = CGRectNull;
}
@end
但是如果你使用一个单独的单例,你需要确保[KeyboardProxy sharedProxy]
从你的应用代理调用,application:didFinishLaunchingWithOptions:
这样单例就不会错过任何通知。