键盘基础

来源:互联网 发布:还有哪些办公软件 编辑:程序博客网 时间:2024/05/29 11:50

键盘

键盘处理在iOS开发中经常用到,尤其在经常性输入内容的应用中。
和键盘联系紧密的控件有:UITextfield、UITextView
键盘的监听通过通知来进行,监听的通知name如下:

//键盘将要出现UIKIT_EXTERN NSNotificationName const UIKeyboardWillShowNotification;//键盘出现UIKIT_EXTERN NSNotificationName const UIKeyboardDidShowNotification;//键盘将要隐藏UIKIT_EXTERN NSNotificationName const UIKeyboardWillHideNotification;//键盘隐藏UIKIT_EXTERN NSNotificationName const UIKeyboardDidHideNotification;//键盘将要改变frameUIKIT_EXTERN NSNotificationName const UIKeyboardWillChangeFrameNotification;//键盘改变frameUIKIT_EXTERN NSNotificationName const UIKeyboardDidChangeFrameNotification;   

注册通知,传递NSNotification参数:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

监听通知:
在参数notification中存在一个字典userInfo,使用如下key获取通知字典内的内容:

//键盘的frameUIKIT_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就可以判断键盘的弹出和消失,这样通过一个方法就可解决。

0 0