UITableViewCell的高度快取
讓UITableViewCell高度自適應的方法有兩種
1、對UITableView進行設定
tableView.rowHeight = UITableViewAutomaticDimension;
2、通過代理返回
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewAutomaticDimension; }
使用自適應高度時,在Cell每次即將被展示出來的時候都會呼叫Cell中的 :arrow_down:方法進行計算。
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority NS_AVAILABLE_IOS(8_0);
但是系統計算行高後並沒有進行快取,每次Cell即將出現的時候都會重新計算一遍高度。
快取高度
我們知道Cell通過systemLayoutSizeFittingSize...
方法獲取高度。
那麼我們需要做的就是呼叫Cell的systemLayoutSizeFittingSize...
方法獲取到高度,然後儲存到Cell對應的資料來源中。
在返回Cell高度的代理方法heightForRowAtIndexPath
中判斷資料來源中是否有高度,如果有高度直接返回,如果沒有高度返回自適應高度列舉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; }