键盘
键盘处理在iOS开发中经常用到,尤其在经常性输入内容的应用中。
和键盘联系紧密的控件有:UITextfield、UITextView
。
键盘的监听通过通知来进行,监听的通知name如下:
//键盘将要出现
UIKIT_EXTERN NSNotificationName const UIKeyboardWillShowNotification;
//键盘出现
UIKIT_EXTERN NSNotificationName const UIKeyboardDidShowNotification;
//键盘将要隐藏
UIKIT_EXTERN NSNotificationName const UIKeyboardWillHideNotification;
//键盘隐藏
UIKIT_EXTERN NSNotificationName const UIKeyboardDidHideNotification;
//键盘将要改变frame
UIKIT_EXTERN NSNotificationName const UIKeyboardWillChangeFrameNotification;
//键盘改变frame
UIKIT_EXTERN NSNotificationName const UIKeyboardDidChangeFrameNotification;
注册通知,传递NSNotification参数:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
监听通知:
在参数notification中存在一个字典userInfo,使用如下key获取通知字典内的内容:
//键盘的frame
UIKIT_EXTERN NSString *const UIKeyboardFrameEndUserInfoKey; // NSValue of CGRect
//键盘弹出的时间
UIKIT_EXTERN NSString *const UIKeyboardAnimationDurationUserInfoKey; // NSNumber of double
在通知里获取键盘的frame和键盘弹出的时间
- (void)keyboardFrameChange:(NSNotification *)notification
{
//键盘字典信息
NSDictionary *userInfo = notification.userInfo;
//键盘frame
CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//动画时间
CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
}
键盘的弹出和消失,也可以注册两个通知来监听键盘的弹出和消失,不过在这两个方法中也是要取得键盘的frame。
可以直接监听键盘frame的改变,通过origin.y
就可以判断键盘的弹出和消失,这样通过一个方法就可解决。