iOS:UITableView键盘弹出定位到编辑位置

问题

之前做过好几个项目,UITableViewCell嵌套着UITextField或者UITextView,当弹起键盘时会遮挡编辑窗口,之前一直用改变UITableViewFrame方式,然后设置UITableViewContentOffset方式滚动到对应的编辑位置,但是这种方式存在着不友好的UI交互。

解决思路

  • 监听键盘UIKeyboardWillShowNotification 和 UIKeyboardWillHideNotification

  • 在键盘弹起的时候改变UITableView的contentInset

  • 调用UITableView的API- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;滚动到指定的位置

  • 键盘弹下时同样改变UITableView的contentInset恢复到原来位置

代码

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    CGFloat height = keyboardRect.size.height;
    NSNumber *durationTime = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:durationTime.floatValue + 0.1 animations:^{

    } completion:^(BOOL finished) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
        /**滚动到指定的cell*/
        [self.tableView scrollToRowAtIndexPath:self.selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSNumber *durationTime = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
  
    [UIView animateWithDuration:durationTime.floatValue animations:^{
        
    }completion:^(BOOL finished) {
        UIEdgeInsets insets = self.tableView.contentInset;
        insets.bottom = 0.0;
        self.tableView.contentInset = insets;
    }];
}

你可能感兴趣的:(iOS:UITableView键盘弹出定位到编辑位置)