2013-03-22 41 views
1

我有一个自定义UITextField类,它需要在显示后抓住键盘的矩形。所以,在课堂上,我听UIKeyboardWillShowNotification,并从UIKeyboardFrameEndUserInfoKey获取键盘的矩形。如果键盘当前没有显示,这很好用。但是,如果键盘已经显示 - 例如当您在文本框之间点击时 - UIKeyboardWillShowNotification只会触发点击第一个文本框。对于其他文本字段,我无法知道键盘的矩形是什么。如果已经显示键盘矩形,我该如何得到它?

任何关于如何在键盘显示屏已被显示后得到的建议

+2

创建的矩形的属性,并设置该属性的值键盘首次出现。 – rdelmar 2013-03-22 04:35:31

回答

1

给你的AppDelegate a keyboardFrame财产。使AppDelegate遵守UIKeyboardWillShowNotificationUIKeyboardWillHideNotification并适当地更新属性。当键盘被隐藏时将属性设置为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:让单身不会错过任何通知。

+0

-1:应用程序委托只能用于初始设置。相反,如果你想要一个共享对象,单身更好。 – 2013-03-22 05:41:53

+1

应用程序委托*是*单例。为什么要打造另一个? – 2013-03-22 05:56:39

+0

请注意,在任何其他代码有机会使键盘出现之前,您将不得不初始化其他单例。应用程序委托的“application:didFinishLaunchingWithOptions:'是适当的地方。所以无论如何,应用程序代表都需要参与。 – 2013-03-22 05:58:57

相关问题