scrollToRowAtIndexPath滚动不到最后一行

在聊天布局中,发送消息你希望滚动到最后一行,直接使用scrollToRowAtIndexPath不会起作用,通常需要这样

  NSIndexPath *bottom = [NSIndexPath indexPathForRow:self.dataAry.count-1 inSection:0];
        dispatch_async(dispatch_get_main_queue(), ^{
         //   [self tableView:self.tableView cellForRowAtIndexPath:bottom];
            [self.tableView scrollToRowAtIndexPath:bottom atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        });

为了使cell自适应,我们可能会用到model计算缓存高度,像下面这样。


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CMAIMessage *messageModel = self.dataAry[indexPath.row];
    NSLog(@"cellHeight:%f",messageModel.cellHeight);
    return messageModel.cellHeight;
}

然而即使我们将scrollToRowAtIndexPath放到了一个队列中,不起作用。
通过打印观察发现不能正确滚动到最后一行的位置是因为:scrollToRowAtIndexPath并不能调用cellForRowAtIndexPath,而直接heightForRow为0。
所以为了解决:我们可以 手动去调用cellForRowAtIndexPath:indexPath]方法

1、

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CMAIMessage *messageModel = self.dataAry[indexPath.row];
    if(messageModel.cellHeight == 0){
        NSLog(@"cellHeight:%f",messageModel.cellHeight);
        [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return messageModel.cellHeight;;
    }
    return messageModel.cellHeight;
}

当然我们还可以直接返回UITableViewAutomaticDimension,这样系统会自动再调用cellForRowAtIndexPath:indexPath,如下2

2、


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CMAIMessage *messageModel = self.dataAry[indexPath.row];
    if(messageModel.cellHeight == 0){
        return UITableViewAutomaticDimension;
    }
    return messageModel.cellHeight;
}

你可能感兴趣的:(scrollToRowAtIndexPath滚动不到最后一行)