UITableView 行高自适应 + 缓存优化

2,872 阅读7分钟
原文链接: www.jianshu.com

学习了 FDTemplateLayoutCell 后,我自己也写了一个 TableView 行高自适应加高度缓存的 Demo,本 Demo 研究实现了其中的最基本算高与缓存功能,仅供大家学习使用。

FDTemplateLayoutCell 原作博客

在开始之前,先让我们了解一些 Runtime 的知识,objc_setAssociatedObjectobjc_getAssociatedObject这两个函数。

让我们来看一个例子

/*
     object 要持有“别的对象”的对象
     key 关联关键字,是一个字符串常量,是一个地址(这里注意,地址必须是不变的,地址不同但是内容相同的也不算同一个key)
     value 也就是值
     policy 这是一个枚举,你可以点进去看看这个枚举是什么:
     OBJC_ASSOCIATION_ASSIGN
     OBJC_ASSOCIATION_RETAIN_NONATOMIC
     OBJC_ASSOCIATION_COPY_NONATOMIC
     OBJC_ASSOCIATION_RETAIN
     OBJC_ASSOCIATION_COPY
     */
    //参数一:需要添加属性的对象 参数二:关联关键字(关联关键字要与get方法中的关键字相同,是一个指针类型) 参数三:属性名 参数四:枚举与@property括号中相同
    objc_setAssociatedObject(self, @"name", name, OBJC_ASSOCIATION_COPY_NONATOMIC);

objc_setAssociatedObject这个函数的意思就是通过一个 key 为一个对象绑定另一个对象

/*
     object 持有“别的对象”的对象,这里指a
     key 关联关键字
     */
     objc_getAssociatedObject(self, @"name");

objc_getAssociatedObject这个函数的意思是通过一个 key 取到一个对象绑定的那个对象

在上面这个例子中,我们使用这两个函数,为self所指的对象通过@"name"这个 key 绑定了一个值为name的对象
Runtime 就说这么多,如果小伙伴们想要更为深入的了解,请自行搜寻相关资料,至于为什么要说这两个函数,请小伙伴们继续往下面看。

————前方高能预警————
下面就是本文的重点了

为 UITableViewCell 创建一个 Category 目的是为其增加两个属性

为 Cell 添加两个属性,一个用来标志此 Cell 只用来计算高度,不进行显示,另一个属性标志是否使用约束来进行计算。添加这两个属性的目的是为了保证每一种类的 Cell 都有一个相应的计算 Cell,而且此种类的计算 Cell 有且只有一个,如果你此时还有些懵逼,那请带着你的疑问继续往下看。
什么?你说 Category 不能添加属性?的确,Category 确实不能添加属性,但是我们有万能的 Runtime 啊,来看看我们是怎么做的

@interface UITableViewCell (HeightCacheCell)

//添加两个属性
@property (assign, nonatomic)BOOL justForCalculate; //只用来计算的标志

@property (assign, nonatomic)BOOL noAuotSizeing; //不依靠约束计算,只进行自适应

@end
@implementation UITableViewCell (HeightCacheCell)


#pragma mark ------ 绑定属性

//justForCall
- (void)setJustForCalculate:(BOOL)justForCalculate{
    objc_setAssociatedObject(self, @selector(justForCalculate), @(justForCalculate), OBJC_ASSOCIATION_RETAIN); //使用get方法名作为key
}

- (BOOL)justForCalculate{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

//noAuotSizeing
- (void)setNoAuotSizeing:(BOOL)noAuotSizeing{
    objc_setAssociatedObject(self, @selector(noAuotSizeing), @(noAuotSizeing), OBJC_ASSOCIATION_RETAIN);
}

- (BOOL)noAuotSizeing{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

@end

重写这两个属性的 get set 方法,并使用刚才学到的两个 Runtime 方法,为 UITableViewCell 绑定了两个对象,这样一来,我们就变相的为 UITableViewCell 添加了两个属性

创建一个 Cache 类,用来缓存相应 Cell 的高度

@interface HeightCache : NSObject

@property (strong, nonatomic)NSMutableDictionary *heightCacheDicV; //竖直行高缓存字典
@property (strong, nonatomic)NSMutableDictionary *heightCacheDicH; //水平行高缓存字典
@property (strong, nonatomic)NSMutableDictionary *heightCacheDicCurrent; //当前行高缓存字典

//制作key
- (NSString *)makeKeyWithIdentifier:(NSString *)identifier indexPath:(NSIndexPath *)indexPath;

//判断高度是否存在
- (BOOL)existInCacheByKey:(NSString *)key;

//查找高度缓存
- (CGFloat)heightFromCacheWithKey:(NSString *)key;

//缓存
- (void)cacheHieght:(CGFloat)hieght key:(NSString *)key;

@end

创建 HeightCache 这样一个类,为其添加了三个字典作为属性,分别存储在手机横屏竖屏下的 Cell 缓存高度,Current 字典为当前手机屏幕状态下的缓存字典,在它的懒加载方法中,我们将判断使用的是横屏缓存字典还是竖屏缓存字典。暴露四个方法,分别是“制作从缓存字典中取缓存高度的 key”、“判断此 key 下是否有缓存高度”、“通过 key 取出缓存高度”、“通过 key 将对应高度缓存”这四个方法。
实现相当简单,这里直接贴上代码,不做过多解释。

@implementation HeightCache

//制作key
- (NSString *)makeKeyWithIdentifier:(NSString *)identifier indexPath:(NSIndexPath *)indexPath{

    return [NSString stringWithFormat:@"%@S%ldR%ld",identifier,indexPath.section,indexPath.row];

}

//判断高度是否存在
- (BOOL)existInCacheByKey:(NSString *)key{
    NSNumber * value = [self.heightCacheDicCurrent objectForKey:key];
    return (value && ![value isEqualToNumber:@-1]);
}

//取出缓存的高度
- (CGFloat)heightFromCacheWithKey:(NSString *)key{
    NSNumber *value = [self.heightCacheDicCurrent objectForKey:key];
    return [value floatValue];
}

//缓存
- (void)cacheHieght:(CGFloat)hieght key:(NSString *)key{
    [self.heightCacheDicCurrent setObject:@(hieght) forKey:key];
}

//lazy
- (NSMutableDictionary *)heightCacheDicH{
    if (!_heightCacheDicH) {
        _heightCacheDicH = [[NSMutableDictionary alloc] init];
    }
    return _heightCacheDicH;
}

- (NSMutableDictionary *)heightCacheDicV{
    if (!_heightCacheDicV) {
        _heightCacheDicV = [[NSMutableDictionary alloc] init];
    }
    return _heightCacheDicV;
}

//根据横竖屏状态选择字典
- (NSMutableDictionary *)heightCacheDicCurrent{
    return UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)?self.heightCacheDicV:self.heightCacheDicH;
}

@end

重点!创建 UITableView 的 Category ,计算 Cell 高度并缓存

我们首先为 UITableView 添加一个 HeightCache 作为属性,方便用来存储高度缓存,这里还是用 Runtime 的方法
#pragma mark ------ 绑定属性

- (HeightCache *)heightCache{
    HeightCache *cache = objc_getAssociatedObject(self, _cmd);
    if (!cache) {
        cache = [[HeightCache alloc] init];
        objc_setAssociatedObject(self, _cmd, cache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return cache;
}

- (void)setHeightCache:(HeightCache *)heightCache{

    objc_setAssociatedObject(self, @selector(heightCache), heightCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}
从复用池中获取一个用于计算的 Cell
//获取一个用于计算高度的Cell
- (__kindof UITableViewCell *)LLQ_CalculateCellWithIdentifier:(NSString *)identifier{

    if (!identifier.length) {
        return nil;
    }

    //runtime获取一个存储cell的字典
    NSMutableDictionary <NSString *, UITableViewCell *> *dicForTheUniqueCalCell = objc_getAssociatedObject(self, _cmd);
    //如果取不到,就绑定一个
    if (!dicForTheUniqueCalCell) {
        dicForTheUniqueCalCell = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, _cmd, dicForTheUniqueCalCell, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    //取出cell,从绑定的字典取用
    UITableViewCell *cell = dicForTheUniqueCalCell[identifier];
    if (!cell) {
        cell = [self dequeueReusableCellWithIdentifier:identifier];
        cell.contentView.translatesAutoresizingMaskIntoConstraints = NO; //设置为NO才能用代码使用AutoLayout
        cell.justForCalculate = YES; //设置只计算
        dicForTheUniqueCalCell[identifier] = cell;
    }

    return cell;

}

此方法中为 UITableView 绑定了一个字典,目的是存储某一种类的 Cell,而区分 Cell 种类的办法就是通过 Cell 的重用标识符。通过重用标识符从字典中获取 Cell,如果获取不到,就从 TableView 的复用池中取出一个此种类的 Cell,并设置只计算属性,存入绑定的字典,这样一来,我们就保证了每种类的 Cell 有且只有一个用来计算。要注意的是,在实际项目使用中我们必须使用-registerClass:forCellReuseIdentifier:-registerNib:forCellReuseIdentifier:其中之一的方法对 Cell 进行注册。

计算 Cell 的高度
//计算cell高度
- (CGFloat)LLQ_CalculateCellHeightWithCell:(UITableViewCell *)cell{

    CGFloat width = self.bounds.size.width;

    //根据辅助视图,调整宽度
    if (cell.accessoryView) {
        width -= cell.accessoryView.bounds.size.width + 16;
    }
    else{
        static const CGFloat accessoryWith[] = {
            [UITableViewCellAccessoryNone] = 0,
            [UITableViewCellAccessoryCheckmark] = 40,
            [UITableViewCellAccessoryDetailButton] = 48,
            [UITableViewCellAccessoryDisclosureIndicator] = 34,
            [UITableViewCellAccessoryDetailDisclosureButton] = 68,
        };
        width -= accessoryWith[cell.accessoryType];
    }

    CGFloat height = 0;

    //非自适应模式,添加约束后计算约束后高度
    if (!cell.noAuotSizeing && width>0) {
        NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:width];
        [cell.contentView addConstraint:widthConstraint];
        //根据约束计算高度
        height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        [cell.contentView removeConstraint:widthConstraint]; //移除约束
    }

    //如果约束添加错误,可能导致计算结果为0,则采用自适应模式计算约束
    if (height == 0) {
        height = [cell sizeThatFits:CGSizeMake(width, 0)].height;
    }

    //还是为0,默认高度
    if (height == 0) {
        height = 44;
    }

    if (self.separatorStyle != UITableViewCellSeparatorStyleNone) {
        height += 1.0/[UIScreen mainScreen].scale;
    }

    return height;
}

首先计算 Cell 的 width,如果有辅助视图,我们还要修正 width,判断是否是 AutoSizeing 模式,来决定使用哪种方式算 Cell 的高度,如果使用约束算高,就是通过添加一个我们算好的固定 width 的约束,从而得出 Cell 的高度。能够这样做的前提是我们在 xib 中使用的 autolayout 约束正确。在最后判断一下有无分割线,做最后一次高度修正。

将上面两个方法整合,给 Cell 填充数据后计算出当前 Cell 的高度
//取出cell并对cell进行操作,然后计算高度
- (CGFloat)LLQ_CalculateCellWithIdentifier:(NSString *)identifier configuration:(void(^)(id cell))configuration{

    if (!identifier.length) {
        return 0;
    }
    UITableViewCell *cell = [self LLQ_CalculateCellWithIdentifier:identifier];
    [cell prepareForReuse]; //放回重用池
    if (configuration) {
        configuration(cell);
    }

    return [self LLQ_CalculateCellHeightWithCell:cell];

}

首先获取一个 Cell 然后将其放回复用池(因为我们在取 Cell 的方法中没有将其放回),然后给 Cell 填充数据,这里使用了 block 将 Cell 传递到外界,填充完数据后使用算高方法计算高度。

计算高度,并将计算的高度缓存,本方法暴露给外界共外界调用
//供外部调用的方法
- (CGFloat)LLQ_CalculateCellWithIdentifer:(NSString *)identifier indexPath:(NSIndexPath *)indexPath configuration:(void(^)(id cell))configuration{

    if (self.bounds.size.width != 0) {
        if (!identifier.length || !indexPath) {
            return 0;
        }
        NSString *key = [self.heightCache makeKeyWithIdentifier:identifier indexPath:indexPath];
        if ([self.heightCache existInCacheByKey:key]) {  //如果有缓存,就取出缓存
            return [self.heightCache heightFromCacheWithKey:key]; //从字典中取出高度
        }
        //没有缓存,计算缓存
        CGFloat height = [self LLQ_CalculateCellWithIdentifier:identifier configuration:configuration];
        //并进行缓存
        [self.heightCache cacheHieght:height key:key];
        return height;
    }

    return 0;
}

首先使用重用标识符和 IndexPath 制作高度缓存的 key,这样制作出的 key 就能保证种类、组、行的唯一性,然后使用这个 key 去取缓存的高度,若没有缓存高度就进行计算。

本 Demo 实现了 TableView 的行高自适应与行高缓存,这只是 FDTemplateLayoutCell 的一部分主要功能,在项目复杂情况下不够适用,比如在移动一个单元格,删除一个单元格等情况时本 Demo 没有相应的处理实现,如果各位小伙伴项目需要,请直接使用 FDTemplateLayoutCell
本 Demo 仅供学习使用。

最后,我还是会按照惯例把 Demo 共享给大家
Demo点这里!点这里!点这里!