IOS键盘遮盖问题解决办法

时间:2021-10-23 20:20:22

1.添加键盘显示和隐藏通知事件响应

<pre name="code" class="objc">  // 添加键盘显示/隐藏的通知
[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWillShow:)

name:UIKeyboardDidShowNotification object:nil];


[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWillHide:)

name:UIKeyboardWillHideNotification object:nil];


2.事件响应 

<pre name="code" class="objc">#pragma mark - Notification Method

///键盘显示事件
- (void) keyboardWillShow:(NSNotification *)notification {


//获取键盘高度,在不同设备上,以及中英文下是不同的
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat offset=输入框下边沿纵坐标-(self.view.frame.size.height-kbHeight);
//将视图上移计算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}];
}
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
// 键盘动画时间
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

//视图下沉恢复原状
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
}];
}