最近项目中用到了在tableView上放UITextField,当UITextField获取焦点时,键盘就会弹起,就会遮挡一部分,这时就需要做一些特殊的处理来防止键盘遮挡tableView,其实思路还是很简单的,系统提供了2个通知,UIKeyboardWillShowNotification和UIKeyboardWillHideNotification,通过名字就能看出来,UIKeyboardWillShowNotification监听的是键盘将要弹出时的事件,UIKeyboardWillHideNotification监听的是键盘将要隐藏时的事件。这两个通知都包含键盘的一些信息,比如通知开始前键盘的frame、收到通知后键盘的高度等等。我们就在UIKeyboardWillShowNotification的通知事件中改变tableView的frame并将其滚动到最底部,在UIKeyboardWillHideNotification的通知事件中将tableView的frame变成原来的即可。下面是具体的代码:
(1)注册通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
(2)添加通知事件:
#pragma mark 键盘将要出现的时候
- (void)keyboardWillShow:(NSNotification *)notification {
CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, UI_SCREEN_HEIGHT - endFrame.size.height);
// 这个动画是为了兼容第三方输入法,如果是系统的输入法直接改变他的ContentOffset即可,默认有动画,但是如果是第三方输入法动画就没有了,所以在这里用键盘的动画来进行弥补
[UIView animateWithDuration:duration.doubleValue animations:^{
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:[curve intValue]];
if (self.tableView.contentSize.height > self.tableView.frame.size.height) {
CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
// 这里的animated属性必须设置为NO(即不用系统的动画),否则会出现问题
[self.tableView setContentOffset:offset animated:NO];
}
}];
}
#pragma mark 键盘将要隐藏
- (void)keyboardWillHide:(NSNotification *)notification {
self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, UI_SCREEN_HEIGHT);
}
(3)移除通知:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];