给你的AppDelegate
a keyboardFrame
财产。使AppDelegate
遵守UIKeyboardWillShowNotification
和UIKeyboardWillHideNotification
并适当地更新属性。当键盘被隐藏时将属性设置为CGRectNull
,或者添加单独的keyboardIsShowing
属性。 (您可以使用CGRectIsNull
功能测试CGRectNull
)
然后任何对象都可以用这个咒语随时检查键盘框架:
[[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:
让单身不会错过任何通知。
创建的矩形的属性,并设置该属性的值键盘首次出现。 – rdelmar 2013-03-22 04:35:31