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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容