您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 動態 Cell 高度計算與緩存實踐

編輯:iOS 程式設計技術

項目裡有一個類似微博的動態 cell,文字與圖片數量都不固定,高度需要動態計算。頻繁計算會拖累滾動流暢度,因此借鑒 FDTemplateLayoutCell 的思路做緩存就很有必要。

一開始我嘗試用 AutoLayout,卻遇到不少問題;換用 FDTemplateLayoutCell 這個自動布局庫後仍有狀況,或許並不完全適配這種場景。最終改回 frame 布局,但 FDTemplateLayoutCell 的緩存機制依然值得借鑒。

我的做法是:先用 frameModel 算出 cell 高度(這部分省略),再著手做緩存。

緩存類的設計

仿照 FD 系列,我寫了一個 UITableView 的分類,並在其中定義了一個 CellHeightCache 類,提供三個方法:

//是否已經緩存了
- (BOOL)existsHeightForKey:(id<NSCopying>)key {
    NSNumber *number = self.mutableCellHeightCaches[key];
    return number && ![number isEqualToNumber:@-1];
}
//緩存高度
- (void)cacheHeight:(CGFloat)height byKey:(id<NSCopying>)key {
    self.mutableCellHeightCaches[key] = @(height);
}
//傳入 key 獲得高度
- (CGFloat)heightForKey:(id<NSCopying>)key {
#if CGFLOAT_IS_DOUBLE
    return [self.mutableCellHeightCaches[key] doubleValue];
#else
    return [self.mutableCellHeightCaches[key] floatValue];
#endif
}

接著在 UITableView 的分類裡寫了兩個對外方法,一個取值、一個存值:

- (CGFloat)getCellHeightCacheWithCacheKey:(NSString *)cacheKey {
    if (!cacheKey) { return 0; }
    //如果已經存在 cell height 則返回
    if ([self.cellHeightCache existsHeightForKey:cacheKey]) {
        CGFloat cachedHeight = [self.cellHeightCache heightForKey:cacheKey];
        return cachedHeight;
    } else {
        return 0;
    }
}
//緩存 cell 的高度
- (void)setCellHeightCacheWithCellHeight:(CGFloat)cellHeight CacheKey:(NSString *)cacheKey {
    [self.cellHeightCache cacheHeight:cellHeight byKey:cacheKey];
}

它們都依賴同一個懶加載方法來取得緩存對象:

- (CellHeightCache *)cellHeightCache {
    CellHeightCache *cache = objc_getAssociatedObject(self, _cmd);
    if (!cache) {
        cache = [CellHeightCache new];
        objc_setAssociatedObject(self, _cmd, cache, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return cache;
}

這裡用到 OC 的 runtime 關聯方法,傳入 value 與 key 對應存儲,取出時再依 key 取值,object 傳入 self 即可:

//傳入 object、key、value 與 policy(存儲方式,類似 copy/retain/assign 等)
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
//傳入 object 和 key 返回 value
id objc_getAssociatedObject(id object, const void *key)

值得注意的是這裡用了 _cmd。它是方法的隱藏參數,代表當前方法的 selector,和 self 一樣每次調用都會傳入,常與關聯方法搭配使用。

在 heightForRowAtIndexPath 中應用

最後在返回行高的地方調用緩存:

CGFloat cellHeight = [tableView getCellHeightCacheWithCacheKey:statusFrame.identifier];
NSLog(@"從緩存取出來的-----%f",cellHeight);
if(!cellHeight){
    statusFrame.status = status;
    cellHeight = statusFrame.cellHeight;
    [tableView setCellHeightCacheWithCellHeight:cellHeight CacheKey:statusFrame.identifier];
}

這樣,動態 cell 的高度緩存就搞定了。

實際效果:

代碼地址:https://github.com/AscenZ/YBDynamicCell

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved