重构:iOS 中 cell 缓存计算高度实现

2020-11-04  本文已影响0人  SoaringHeart

之前用过字典缓存高度,["(indexPath.section),(indexPath.row)" : "计算的高度"],可以实现但是不够优雅,每一个页面需要计算 cell 高度的时候的时候都需要一个字典变量,代码冗余;
灵光一闪:为什么不能将值存储到模型中,成为一个对应键的缓存高度。当 indexPath.row 为 1 时需要动态计算高度,高度为0时计算并缓存,快速滑动时只计算一次。优点:整个代码只给模型添加了一个变量。页面没有引入其他的全局变量,并且降低了内存使用。支持多个键值高度计算并缓存。

代码如下:

@interface PKFeedbackDetailModel : NSObject

@property (nonatomic, copy) NSString *title;

@property (nonatomic, copy) NSString *content;
///对应 content 的缓存高度变量
@property (nonatomic, assign) CGFloat contentHeight;

@property (nonatomic, assign) NSInteger create_at;
@property (nonatomic, copy, readonly) NSString *create_atDes;

@property (nonatomic, copy) NSString *username;

@end
extension PKFeedbackListController: UITableViewDataSource, UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataList.count;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3;
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let model = dataList[indexPath.section] as? PKFeedbackDetailModel else { return 0 }
        
        var height = tableView.rowHeight
        switch indexPath.row {
        case 0:
            height = 25
        case 1:
            if model.contentHeight <= 0 {
                let contentHeight = sizeWithText(model.content, font: 14, width: tableView.bounds.width - 30).height
                model.contentHeight = ceil(contentHeight) + 16
            }
            height = model.contentHeight

        case 2:
            height = model.image.count == 0 ? 0 : 95
        default:
            break
        }
        return height
    }

上一篇下一篇

猜你喜欢

热点阅读