讓UITableViewCell高度自適應(yīng)的方法有兩種
1体谒、對(duì)UITableView進(jìn)行設(shè)置
tableView.rowHeight = UITableViewAutomaticDimension;
2唾那、通過(guò)代理返回
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
使用自適應(yīng)高度時(shí),在Cell每次即將被展示出來(lái)的時(shí)候都會(huì)調(diào)用Cell中的 ??方法進(jìn)行計(jì)算。
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority NS_AVAILABLE_IOS(8_0);
但是系統(tǒng)計(jì)算行高后并沒(méi)有進(jìn)行緩存刑峡,每次Cell即將出現(xiàn)的時(shí)候都會(huì)重新計(jì)算一遍高度纵菌。
緩存高度
我們知道Cell通過(guò)systemLayoutSizeFittingSize...
方法獲取高度斥赋。
那么我們需要做的就是調(diào)用Cell的systemLayoutSizeFittingSize...
方法獲取到高度,然后存儲(chǔ)到Cell對(duì)應(yīng)的數(shù)據(jù)源中产艾。
在返回Cell高度的代理方法heightForRowAtIndexPath
中判斷數(shù)據(jù)源中是否有高度疤剑,如果有高度直接返回,如果沒(méi)有高度返回自適應(yīng)高度枚舉UITableViewAutomaticDimension
闷堡。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
HLCellHeightCacheModel *model = self.datas[indexPath.row];
return model.cellHeight ? : UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
HLCellHeightCacheModel *model = self.datas[indexPath.row];
HLCellHeightCacheCell *cell = [HLCellHeightCacheCell cellWithTableView:tableView identifier:@"HLCellHeightCacheCellID"];
[cell updateView:model];
if (!model.cellHeight) {
// 高度緩存
CGFloat height = [cell systemLayoutSizeFittingSize:CGSizeMake(tableView.frame.size.width, 0) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel].height;
model.cellHeight = height;
}
return cell;
}