- 界面操作的时候经常需要进行输入操作,键盘会有遮挡UI的情况,这是就需要对键盘进行监听,做对应处理
控制器加入对键盘事件的监听,控制器加入代码
[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
实现键盘出现和消失的代理并计算键盘高度,按需求操作UI
1.键盘出现和消失
-(void)keyboardWillAppear:(NSNotification *)notification{
float keyboardH = [self keyboardEndingFrameHeight:notification.userInfo];
[UIView animateWithDuration:0.2 animations:^{
self.contentView.frame = CGRectMake(0,kDeviceHeight-contentView.height-keyboardH,kDeviceWidth,contentView.height);
}]; }
-(void)keyboardWillDisappear:(NSNotification *)note {
self.contentView.frame = CGRectMake(0,kDeviceHeight-contentView.height,kDeviceWidth,contentView.height); }
2.下面也是最重要的方法,获取键盘高度
-(CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo {
CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
CGRect keyboardEndingFrame = [selfconvertRect:keyboardEndingUncorrectedFrame fromView:nil];
return keyboardEndingFrame.size.height;}