1. 场景还原
如图,三种cell的tableView:
三种cell.gif
后台返回的json数据如下:
{    "result": true,    "data": {        "list": [ {                 "type": 0,                 "title": "第一种cell,图片在左边",                 "image": "number_1"
                 }, {                 "type": 1,                 "title": "第二种cell,图片在右边",                 "image": "number_2"
                 }, {                 "type": 2,                 "title": "第三种cell,图片在中间",                 "image": "number_3"
                 }, {                 "type": 0,                 "title": "老子反手就是一个呵呵哒",                 "image": "number_1"
                 }]
    },    "msg": "ok",    "code": 200,    "executed": "0.0320830345"}类似于这种同种model,多种cell的tableView相信不少开发者在实际项目开发中都遇到过,我分享一下我的做法,谨以抛砖引玉。
2. 文件组织
2.1 什么是抽象基类?
只用于继承、不用于实例化的类。
3. 类族
类族,就是将子类的实现细节隐藏在抽象基类中。(个人理解)
这是抽象基类cell代码:
+ (instancetype)cellWithType:(CQClassClusterType)type {    // 根据type创建对应的子类cell
    switch (type) {        case CQClassClusterTypeA:
        {            return [[CQClassClusterCellA alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQClassClusterCellAReuseID];
        }            break;            
        case CQClassClusterTypeB:
        {            return [[CQClassClusterCellB alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQClassClusterCellBReuseID];
        }            break;            
        case CQClassClusterTypeC:
        {            return [[CQClassClusterCellC alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQClassClusterCellCReuseID];
        }            break;
    }
}使用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CQClassClusterModel *model = self.dataArray[indexPath.row];
    CQClassClusterBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:model.cellReuseID];    if (!cell) {        // 类族模式
        cell = [CQClassClusterBaseCell cellWithType:model.type];
    }
    [cell setModel:model];    return cell;
}4. demo
https://github.com/CaiWanFeng/iOS_Storage
demo所在位置:
作者:无夜之星辰
链接:https://www.jianshu.com/p/0dbe99e914ff