ios - uitableviewcell动态高度如何优化性能?
高洛峰
高洛峰 2017-04-17 13:28:28
[iOS讨论组]

我目前的方法是使用缓存。因为 heightForRowAtIndexPath 先于 cellForRowAtIndexPath 调用。那么在 heightForRowAtIndexPath 的时候初始化 cell,缓存起来。
cellForRowAtIndexPath 的时候,从缓存读取。

现在问题来了。。。。。

因为cell自身的复用机制所致,滚动的时候,出现一些问题。
如果彻底干掉cell自身飞复用机制,那么每次渲染初始化cell,太耗时间和内存了。

怎么都不行,如何是好?

我的代码如下:

objc//计算cell的高度,这里初始化cell了。那么缓存起来。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    FeedCell *cell = [self getCellFromIndexPath:indexPath];
    return cell.frame.size.height;
}



//把Cell复用逻辑写在一个方法里
- (FeedCell*)getCellFromIndexPath:(NSIndexPath*)indexPath
{
    Post *post = [self.dataSource objectAtIndex:indexPath.row];
    NSString *key = [NSString stringWithFormat:@"%@%d_%d%d", CellIdentifier, post.pid, indexPath.row, indexPath.section];
    FeedCell *cell = [self.cellCache objectForKey:key];//看看是否有cell的缓存。
    if (!cell) {

        //系统自身的复用机制。
        cell = [self.feedTableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell)
        {
            cell = [[FeedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }


        [cell setAutoFrame];

        cell.tag = post.pid;
        [self.cellCache setObject:cell forKey:key];
    }

    return cell;
}




//因为计算cell高度的时候已经初始化了。那么这里从缓存读取。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    return [self getCellFromIndexPath:indexPath];

}

编辑器对大片代码没法高亮,我反复折腾很久,代码排版不尽人意。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
阿神

只支持 iOS 7 以上的,用上 tableView:estimatedHeightForRowAtIndexPath: 方法;
一般滚动时的卡顿不会是 cell 自身的复用机制的问题,有时候是重用机制没有生效所至,有时候是别的地方代码写得不够符合规范。

PHP中文网

同学,你为什么要缓存cell,你直接缓存height还可以理解,因为你缓存的cell还是会被tableView重用而修改。JeOam提到的是正确的方法,另外如果使用auto layout,要避免cell设计的过于复杂,一般来说即使你不用tableView:estimatedHeightForRowAtIndexPath:也是很流畅的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号