美文网首页
iOS 11后的UITableView-reloadData漂移

iOS 11后的UITableView-reloadData漂移

作者: AnderQZ | 来源:发表于2020-05-26 17:07 被阅读0次

问题:在UITableView中,如果是iOS 11系统,Cell内容比较多,例如图片加文字,又是用到AutoLayout,有分页加载数据,那就有可能出现一种奇怪的情况,在加载数据第二页数据时,出现定位不准的情况,本来应该显示在第十行的,却跑到了第十五行去了,这确实难以接受的bug。

经过一番查询,才发现,原来这么多人喜欢复制粘贴内容。。。🥶
写的基本都是说:iOS 11后系统默认开启了self-sizing,官方文档是这样解释的.......
通过这段代码可以解决问题:

 self.tableView.estimatedRowHeight = 0;
 self.tableView.estimatedSectionHeaderHeight = 0;
 self.tableView.estimatedSectionFooterHeight = 0;

但是!如果你用了自动计算rowHeight,那这个办法是完全没用的,解决方法略。就这破玩意,我搜索出几十份copy的,实在难以理解。🥶

以下是我找到另外一个大神写的解决办法,使用一个NSMutableDictionary来记录rowHeight,然后willDisplayCell时,缓存一下rowHeight,然后在estimatedHeightForRowAtIndexPath中使用缓存的高度即可。具体代码如下:

- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
[_cellHeightsDic setObject:@(cell.frame.size.height) forKey:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
NSNumber *height = [_cellHeightsDic objectForKey:indexPath];
if (height) {
    return height.doubleValue;
}

return UITableViewAutomaticDimension;
}

别忘了要先初始化_cellHeightsDic = @{}.mutableCopy;

参考来源:https://www.meiwen.com.cn/subject/fivtwftx.html

相关文章

网友评论

      本文标题:iOS 11后的UITableView-reloadData漂移

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