美文网首页iOS日常开发iOS 进阶
iOS:UITableView键盘弹出定位到编辑位置

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

作者: 风与鸾 | 来源:发表于2018-03-14 17:47 被阅读5次

    问题

    之前做过好几个项目,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键盘弹出定位到编辑位置

        本文链接:https://www.haomeiwen.com/subject/zttqqftx.html