iOS关于键盘弹出后tableview的滑动问题

江枫思渺然 提交于 2020-03-02 00:04:18
在键盘处理的过程中,最容易出现问题的就是,在键盘监听事件中,tableView的frame的修改,网上分享的大部分都是修改frame,这样会导致tableView的cell被遮挡,可能引起获取不到cell的indexPath,导致无法滚动到指定位置
还有一点就是UITableViewController的使用,如果直接使用UITableViewController,键盘弹出事件是不用我们开发者去处理的,UITableViewController自动帮我们实现了,也就是点击cell中的输入框,就可以直接弹出到可见区域,进行编辑。但UITableViewController的view是一个tableView,也就是说,你想在这个controller里加一个固定位置的view,是不可能的,这就牺牲了页面的可定制性
 
- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification {
    NSDictionary* info = [aNotification userInfo];
    // 注意不要用UIKeyboardFrameBeginUserInfoKey,第三方键盘可能会存在高度不准,相差40高度的问题
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    // 修改滚动天和tableView的contentInset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
    
    // 跳转到当前点击的输入框所在的cell
    [UIView animateWithDuration:0.5 animations:^{
        [self.tableView scrollToRowAtIndexPath:_indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }];
}

- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}
这里我们需要添加对键盘事件通知的检测,而对自己的tableView所做的改变,不是frame,而是contentInset,这样就可以保证tableView的滚动范围为键盘上方的区域,可见区域为整个屏幕。
_indexPath全局变量,需要在textfield的代理中去获取,获取到正在编辑的输入框所在的cell。
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textField.superview.superview];
    _indexPath = indexPath;
}
 
 

作者:翻炒吧蛋滚饭
链接:https://www.jianshu.com/p/c01d19b81eed
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!