iOS UITableView 无法滚动到底部!

前言

使用了第三方布局框架MyLayout(地址)来创建IM聊天界面。
因为只需要创建一套UI即可实现两套布局
设置一个属性layoutTransform即可。


跳动问题

刷新界面时,因为采用了动态高度来计算 cell 高度
导致了高度估算不准
所以会导致跳动问题

办法:

  • 1.不使用动态高度
  • 2.手动计算 cell 高度,然后缓存到对应的 模型 上。系统调用方法的顺序如下:
    • 2.1 在方法 tableView:cellForRowAtIndexPath:内,给 cell 模型赋值时,计算高度。
    • 2.2 在方法 tableView:heightForRowAtIndexPath:内,取出对应模型,返回高度。

滚动问题

添加数据源,列表插入数据,滚动到列表底部:

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataArray.count inSection:0];
    [_dataArray addObject:model];
    [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];

就是这么几行简单的代码
列表就是滚动不到底部!

找了好多资源
找了好多Demo

就是没发现问题所在 T_T


Style

当列表初始化时,设置 styleGrouped
发现列表可以滚动到底部了

进一步测试
又不行了

这个只有在列表
已经滚动到底部的时候
才能生效 T_T


系统方法

UITableView 的一个代理方法 insertRowsAtIndexPaths:withRowAnimation:在被调用时
会调用另外一个代理方法:tableView:heightForRowAtIndexPath:
而这个方法
只是取了对应模型
然后返回 cell 高度

但是 cell 数量超过一屏时
并没有调用 tableView:cellForRowAtIndexPath: 这个方法
所以
上面返回的模型高度是 0!

天真的以为
系统会先调用tableView:cellForRowAtIndexPath: 获取 cell
然后调用 tableView:heightForRowAtIndexPath: 返回高度

办法:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JHMessageModel *model = _dataArray[indexPath.row];
    if (model.height == 0) { // 高度为0时,手动调用方法,计算高度。
        [self tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    return model.height;
}

终于解决了!!!
不管是 styleplain 还是 grouped
都没问题了


最后

没有Demo提供
https://github.com/xjh093


发布了201 篇原创文章 · 获赞 220 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/xjh093/article/details/95060357
今日推荐