iOS中键盘遮挡问题很常见,网上有很多解决方案,现在要说的这种也是其中一种。很多网友的解决方案很局限,没考虑适配等问题。
这里介绍的解决方案是通过Apple系统提供的通知来解决问题,NSNotification中包含了键盘的一些信息,这个可以充分利用之。
首先监听以下两个通知,系统会负责发送通知,当然你自己也可以发送。
// 监听键盘的即将显示事件. UIKeyboardWillShowNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// 监听键盘即将消失的事件. UIKeyboardWillHideNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
实现通知处理方法
- (void) keyboardWillShow:(NSNotification *)notify {
//这里只写了关键代码,细节根据自己的情况来定,sv为弹出键盘的视图,UITextField
CGFloat kbHeight = [[notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//获取键盘高度,在不同设备上,以及中英文下是不同的,很多网友的解决方案都把它定死了。
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat screenHeight = self.view.bounds.size.height;
CGFloat viewBottom = sv.frame.origin.y + sv.frame.size.height;
if (viewBottom + kbHeight < screenHeight) return;//若键盘没有遮挡住视图则不进行整个视图上移
// 键盘会盖住输入框, 要移动整个view了
delta = viewBottom + kbHeight - screenHeight + 50;
// masonry的地方了 mas_updateConstraints 更新superView的约束,这里利用第三方库进行了重新自动布局,如果你不是自动布局,这里换成你的视图上移动画即可
[superView mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top).offset(-delta);
}];
[UIView animateWithDuration:duration animations:^void(void){
// superView来重新布局
[superView layoutIfNeeded];
}];
}
- (void) keyboardWillHidden:(NSNotification *)notify {//键盘消失
// 键盘动画时间
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[superView mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top);
}];
[UIView animateWithDuration:duration animations:^{
[superView layoutIfNeeded];
}];
delta = 0.0f;
}