美文网首页iOS 进阶
关于iOS中刷新单行cell抖动的问题

关于iOS中刷新单行cell抖动的问题

作者: 跨行程序员 | 来源:发表于2019-01-04 11:36 被阅读152次

    由于项目中需要使用自动布局,因此本人采用masonry布局。但在布局之后,屏幕刷新调用reloadData会间歇性的抖动,体验及其差。

    产生原因:

    在使用自动布局之后,UITableViewAutomaticDimension 高度自动适应,就是每次计算高度的时候产生闪动,原因是这个自动布局计算cell高度的时候出现问题。

    解决方法:

    于是查看其他大佬的文章发现几乎全部采用预设高度为0来进行解决,解决方案如下:

            tableView.estimatedRowHeight = 1;

            tableView.estimatedSectionHeaderHeight = 0;

            tableView.estimatedSectionFooterHeight = 0;

    经过调试发现,采用固定高度布局时,此方法有效可行。但在自动布局的情况下,该解决方案会导致cell无法展开,实现高度自适应。

    后来在@草尘大佬的一篇文章中看到了完美的解决方案,在这里分享给大家:

    // 声明单元格高度字典

    NSMutableDictionary *cellHeightsDictionary;

    // 代码初始化

    cellHeightsDictionary = @{}.mutableCopy;

    // 声明表的动态行高度,并在单元格中创建正确的约束

    tableView.rowHeight = UITableViewAutomaticDimension;

    // 保存行高

    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];

    }

    //给出准确的高度值

    - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSNumber *height = [cellHeightsDictionary objectForKey:indexPath];

    if (height) return height.doubleValue;

    return UITableViewAutomaticDimension;

    }

    这样便可以完美的解决了。希望对您有帮助!

    相关文章

      网友评论

        本文标题:关于iOS中刷新单行cell抖动的问题

        本文链接:https://www.haomeiwen.com/subject/spomrttx.html