UITableView上的UITextField防止被键盘遮挡

最近项目中用到了在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];



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值