股票场内基金交易,没时间盯盘?
介绍
UITableView+FDTemplateLayoutCell 是一个由国人团队开发的优化计算 UITableViewCell 高度的轻量级框架(GitHub 地址),由于实现逻辑简明清晰,代码也不复杂,非常适合作为新手学习其他著名却庞大的开源项目的“入门教材”。
开发者之一的阳神也通过一篇博客介绍了 UITableViewCell 高度计算(尤其是 autoLayout 自动高度计算)的方方面面。总结一下的话就是:
- iOS8 之前虽然采用 autoLayout 相比 frame layout 得手动计算已经简化了不少(设置 estimatedRowHeight 属性并对约束设置正确的 cell 的 contentView 执行 systemLayoutSizeFittingSize: 方法),但还是需要一些模式化步骤,同时还可能遇到一些蛋疼的问题比如 UILabel 折行时的高度计算;
- iOS8 推出 self-sizing cell 后,一切都变得轻松无比——做好约束后,直接设置 estimatedRowHeight 就好了。然而事情并不简单,一来我们依然需要做 iOS7 的适配,二来 self-sizing 并不存在缓存机制,不论何时都会重新计算 cell 高度,导致 iOS8 下页面滑动时会有明显的卡顿。
因此,这个框架的目的,引用阳神的原话,就是“既有 iOS8 self-sizing 功能简单的 API,又可以达到 iOS7 流畅的滑动效果,还保持了最低支持 iOS6”。
注意:这篇文章只进行框架中最主要的 autoLayout 部分介绍,frame layout 部分请自行查看框架说明。
使用
-
引用 UITableView+FDTemplateLayoutCell.h 类;
-
如果是用代码或 XIB 创建的 cell,需要先进行注册(类似 UICollectionView):
123- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier;- (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier; -
在 tableView: heightForRowAtIndexPath: 代理方法中调用以下三个方法之一完成高度获取:
123456789101112131415161718/*identifier 即 cell 的 identifier;configuration block 中的代码应与数据源方法 tableView: cellForRowAtIndexPath: 中对 cell 的设置代码相同方法内部将根据以上两个参数创建与 cell 对应的 template layout cell,这个 cell 只进行高度计算,不会显示到屏幕上*/// 返回计算好的高度(无缓存)- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier configuration:(void (^)(id cell))configuration;// 返回计算好的高度,并根据 indexPath 内部创建与之相应的二维数组缓存高度- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configuration;// 返回计算好的高度,内部创建一个字典缓存高度并由使用者指定 key- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByKey:(id<NSCopying>)key configuration:(void (^)(id cell))configuration;一般来说 cacheByIndexPath: 方法最为“傻瓜”,可以直接搞定所用问题。cacheByKey: 方法稍显复杂(需要关注数据刷新),但在缓存机制上相比 cacheByIndexPath: 方法更为高效。因此,像类似微博、新闻这种会拥有唯一标识的 cell 数据模型,更建议使用cacheByKey: 方法。
-
数据源变动时的缓存处理是个值得关注的问题。
对于 cacheByIndexPath: 方法,框架内对 9 个触发 UITableView 刷新机制的公有方法分别进行了处理,保证缓存数组的正确;同时,还提供了一个 UITableView 分类方法:
12- (void)fd_reloadDataWithoutInvalidateIndexPathHeightCache;用于需要刷新数据但不想移除原有缓存数据(框架内对 reloadData 方法的处理是清空缓存)时调用,比如常见的“下拉加载更多数据”操作。
对于 cacheByKey: 方法,当 cell 高度发生改变时,必须手动处理:
12345// 移除 key 对应的高度缓存[tableView.fd_keyedHeightCache invalidateHeightForKey:key];// 移除所有高度缓存[tableView.fd_keyedHeightCache invalidateAllHeightCache]; -
如果需要查看 debug 打印信息,设置 fd_debugLogEnabled 属性:
12tableView.fd_debugLogEnabled = YES;
框架也为 UITableViewHeaderFooterView 设计了相应方法,因为和 UITableViewCell 相似,这里就不另行介绍了。
框架分析
由于采用了分类机制,因此框架中大量使用 runtime 的关联对象(Associated Object)进行公有和私有变量的实现,不了解的童鞋可以网上搜索一下相关概念。
结构
框架提供了 4 个类,其中 UITableView+FDTemplateLayoutCellDebug 类用于打印 debug 信息,并无其它作用。主要功能由另外 3 个类提供。
- UITableView+FDTemplateLayoutCell:主类,提供高度获取方法;
- UITableView+FDIndexPathHeightCache:创建了一个用于 cacheByIndexPath: 方法的缓存类 FDIndexPathHeightCache;
- UITableView+FDKeyedHeightCache:创建了一个用于 cacheByKey: 方法的缓存类 FDKeyedHeightCache。
高度获取
流程
我们直接以 cacheByIndexPath: 方法源码为例进行了解(cacheByKey: 方法的实现大同小异)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configuration { // 1. 如果 identifier 和 indexPath 为空,返回高度为 0 if (!identifier || !indexPath) { return 0; } // 2. 通过 FDIndexPathHeightCache 类声明的方法检查是否存在相应缓存 if ([self.fd_indexPathHeightCache existsHeightAtIndexPath:indexPath]) { // 打印 debug 信息 [self fd_debugLog:[NSString stringWithFormat:@"hit cache by index path[%@:%@] - %@", @(indexPath.section), @(indexPath.row), @([self.fd_indexPathHeightCache heightForIndexPath:indexPath])]]; // 提取并返回对应缓存中的额高度 return [self.fd_indexPathHeightCache heightForIndexPath:indexPath]; } // 3. 如果没有缓存,通过 fd_heightForCellWithIdentifier: configuration: 方法计算获得 cell 高度 CGFloat height = [self fd_heightForCellWithIdentifier:identifier configuration:configuration]; // 4. 通过 FDIndexPathHeightCache 类声明的方法将高度存入缓存 [self.fd_indexPathHeightCache cacheHeight:height byIndexPath:indexPath]; // 打印 debug 信息 [self fd_debugLog:[NSString stringWithFormat: @"cached by index path[%@:%@] - %@", @(indexPath.section), @(indexPath.row), @(height)]]; return height; } |
缓存相关部分将在下面介绍,这里着重了解一下如何计算获得 cell 高度。
高度计算
fd_heightForCellWithIdentifier: configuration: 方法会根据 identifier 以及 configuration block 提供一个和 cell 布局相同的 template layout cell,并将其传入 fd_systemFittingHeightForConfiguratedCell: 这个私有方法返回计算出的高度。
fd_systemFittingHeightForConfiguratedCell: 方法明确给出了计算流程的注释:
If not using auto layout, you have to override “-sizeThatFits:” to provide a fitting size by yourself. This is the same height calculation passes used in iOS8 self-sizing cell’s implementation.
- Try “- systemLayoutSizeFittingSize:” first
- Warning once if step 1 still returns 0 when using AutoLayout
- Try “- sizeThatFits:” if step 1 returns 0
- Use a valid height or default row height (44) if not exist one
下面给出一些关键点的代码:
关于 UILabel 的折行
框架的做法相当直接:获取当前 contentView 的宽度并添加为其约束,限制 UILabel 水平方向的展开,计算完成后移除。
-
获取当前 contentView 的宽度:
123456789101112131415CGFloat contentViewWidth = CGRectGetWidth(self.frame);// 考虑存在 accessoryView 或者 accessoryType 的情况if (cell.accessoryView) {contentViewWidth -= 16 + CGRectGetWidth(cell.accessoryView.frame);} else {static const CGFloat systemAccessoryWidths[] = {[UITableViewCellAccessoryNone] = 0,[UITableViewCellAccessoryDisclosureIndicator] = 34,[UITableViewCellAccessoryDetailDisclosureButton] = 68,[UITableViewCellAccessoryCheckmark] = 40,[UITableViewCellAccessoryDetailButton] = 48};contentViewWidth -= systemAccessoryWidths[cell.accessoryType];} -
添加约束并进行高度计算:
12345678// 添加约束NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];[cell.contentView addConstraint:widthFenceConstraint];// 计算高度fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;// 移除约束[cell.contentView removeConstraint:widthFenceConstraint];
注意分格线高度
这也是非常容易遗漏的一点:
1 2 3 4 5 |
// Add 1px extra space for separator line if needed, simulating default UITableViewCell. if (self.separatorStyle != UITableViewCellSeparatorStyleNone) { fittingHeight += 1.0 / [UIScreen mainScreen].scale; } |
缓存
FDIndexPathHeightCache
外部接口:
1 2 3 4 5 6 7 8 9 10 11 |
// 当前 indexPath 是否存在缓存 - (BOOL)existsHeightAtIndexPath:(NSIndexPath *)indexPath; // 存入缓存 - (void)cacheHeight:(CGFloat)height byIndexPath:(NSIndexPath *)indexPath; // 从缓存读取高度 - (CGFloat)heightForIndexPath:(NSIndexPath *)indexPath; // 移除指定 indexPath 的缓存 - (void)invalidateHeightAtIndexPath:(NSIndexPath *)indexPath; // 移除所有缓存 - (void)invalidateAllHeightCache; |
其内部针对横屏和竖屏声明了 2 个以 indexPath 为索引的二维数组来存储高度:
1 2 3 4 5 6 7 |
typedef NSMutableArray<NSMutableArray<NSNumber *> *> FDIndexPathHeightsBySection; @interface FDIndexPathHeightCache () @property (nonatomic, strong) FDIndexPathHeightsBySection *heightsBySectionForPortrait; @property (nonatomic, strong) FDIndexPathHeightsBySection *heightsBySectionForLandscape; @end |
更新处理
框架声明了一个 tableView 分类 UITableView (FDIndexPathHeightCacheInvalidation),利用 runtime 的 method_exchangeImplementations 函数对 UITableView 中触发刷新的方法做了替换,以进行相应的缓存调整:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@implementation UITableView (FDIndexPathHeightCacheInvalidation) + (void)load { // UITableView 中所有触发刷新的公共方法 SEL selectors[] = { @selector(reloadData), @selector(insertSections:withRowAnimation:), @selector(deleteSections:withRowAnimation:), @selector(reloadSections:withRowAnimation:), @selector(moveSection:toSection:), @selector(insertRowsAtIndexPaths:withRowAnimation:), @selector(deleteRowsAtIndexPaths:withRowAnimation:), @selector(reloadRowsAtIndexPaths:withRowAnimation:), @selector(moveRowAtIndexPath:toIndexPath:) }; // 用分类中以“fd_”为前缀的方法替换 for (NSUInteger index = 0; index < sizeof(selectors) / sizeof(SEL); ++index) { SEL originalSelector = selectors[index]; SEL swizzledSelector = NSSelectorFromString([@"fd_" stringByAppendingString:NSStringFromSelector(originalSelector)]); Method originalMethod = class_getInstanceMethod(self, originalSelector); Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector); method_exchangeImplementations(originalMethod, swizzledMethod); } } |
FDKeyedHeightCache
相比于 FDIndexPathHeightCache 中较为繁琐的数组操作,FDKeyedHeightCache 显得简洁了许多(当然代价是高度变化时的缓存操作得使用者亲力亲为)。外部接口:
1 2 3 4 5 6 7 8 |
- (BOOL)existsHeightForKey:(id<NSCopying>)key; - (void)cacheHeight:(CGFloat)height byKey:(id<NSCopying>)key; - (CGFloat)heightForKey:(id<NSCopying>)key; // Invalidation - (void)invalidateHeightForKey:(id<NSCopying>)key; - (void)invalidateAllHeightCache; |
内部采用以 key 为索引的字典存储高度:
1 2 3 4 5 |
@interface FDKeyedHeightCache () @property (nonatomic, strong) NSMutableDictionary<id<NSCopying>, NSNumber *> *mutableHeightsByKeyForPortrait; @property (nonatomic, strong) NSMutableDictionary<id<NSCopying>, NSNumber *> *mutableHeightsByKeyForLandscape; @end |
由于采用字典缓存,自然不用关心 cell 插入、删除、移动等造成的缓存数组排列问题,但是当 cell 高度发生改变时,我们也无法像数组那样根据 IndexPath 索引到对应的缓存,因此只能像上文“使用”部分说明的一样,进行手动处理。
想获得去掉 5 元限制的证券账户吗?

如果您想去掉最低交易佣金 5 元限制,使用微信扫描左边小程序二维码,访问微信小程序「优财助手」,点击底部菜单「福利」,阅读文章「通过优财开证券账户无最低交易佣金 5 元限制」,按照文章步骤操作即可获得免 5 元证券账户,股票基金交易手续费率万 2.5。
请注意,一定要按照文章描述严格操作,如错误开户是无法获得免 5 元证券账户的。