iOS UITableView 返回的 indexPath.row 不是从 0 开始的

0x00 下标从4开始!?

封装了一个包含TableView的视图
使用的时候
创建了一个子类来用
把这个子类视图放在了一个嵌套了多层的视图内
一开始发现触摸视图时会抖动
为何会抖动呢?

在方法tableView:cellForRowAtIndexPath:内打印日志
居然是这种!!
在这里插入图片描述
怎么会直接从4开始!?


0x01 代理方法

之前在控制器内的写法是:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Model *model = _dataArray[indexPath.row];
    return model.cellHeight;
}

model.cellHeight是不会为0

但是,在视图嵌套层级比较多的情况下
model.cellHeight全是0

所以
不管是在控制器内
还是在其他视图内
保险的写法是:
加上一个是否为0的判断

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Model *model = _dataArray[indexPath.row];
    if (model.cellHeight == 0) {
        // 这个代理会给cell的模型赋值,并计算cell高度,缓存在model中
        [self tableView:tableView cellForRowAtIndexPath:indexPath]; 
    }
    return model.cellHeight;
}


一套轻量级的布局框架

https://github.com/xjh093/JHFrameLayout


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

猜你喜欢

转载自blog.csdn.net/xjh093/article/details/100315962