ios键盘弹起tableView的滑动区域问题

在iOS项目开发过程中,经常需要点击textview弹起键盘,但弹起键盘后tableView的可见区域就变小了,如果这时tableView不能在可见区域内滑动,那tableView的内容就不能在键盘弹起的情况下完全显示,这样用户体验就不好了。下面提供一种解决方法。

由于大部分控制器类都需要用到tableView,为此可以写一个公共的父类BaseTableViewController继承自UIViewController,里面初始化tableView并实现其代理方法,设置一个属性

@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;

核心代码如下:

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    

    [self.view endEditing:YES];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}


- (void)dealloc {

    NSLog(@"dealloc %@", [self class]);

}


#pragma mark - Keyboard

- (void)keyboardWillShow:(NSNotification *)notification {

    if (!self.tapGesture) {

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];

        tap.cancelsTouchesInView = NO;

        [self.view addGestureRecognizer:tap];

        self.tapGesture = tap;

    }

    

    CGRect keyboardBounds = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, keyboardBounds.size.height, 0);


}


- (void)keyboardWillHide:(NSNotification *)notification {

    [self.view removeGestureRecognizer:self.tapGesture];

    self.tapGesture = nil;

    

    self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, 0, 0);

}


- (void)viewTapped:(id)sender {

    [self.view endEditing:YES];

}


这样子类在继承父类BaseTableViewController时,可在键盘弹起的情况下滑动tableView显示所有内容。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值