iOS tableView高度缓存

Posted 简简单单,平平淡淡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS tableView高度缓存相关的知识,希望对你有一定的参考价值。

tableView计算完高度后,把高度缓存起来,避免下次重复计算,以减少不必要的消耗

// declare cellHeightsDictionary
NSMutableDictionary *cellHeightsDictionary;
 
// initialize in code (thanks to @Gerharbo)
cellHeightsDictionary = @{}.mutableCopy;
 
// declare table dynamic row height and create correct constraints in cells
tableView.rowHeight = UITableViewAutomaticDimension;
 
// save height
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];
}
 
// give exact height value
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *height = [cellHeightsDictionary objectForKey:indexPath];
    if (height) return height.doubleValue;
    return UITableViewAutomaticDimension;
}

以上是关于iOS tableView高度缓存的主要内容,如果未能解决你的问题,请参考以下文章