键盘基础

键盘

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值