为了账号安全,请及时绑定邮箱和手机立即绑定

iOS | “类族”的实际运用

标签:
iOS

1. 场景还原

如图,三种cell的tableView:

290

三种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. 文件组织

281

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://img1.sycdn.imooc.com//5d5e40f500013eda08930725.png


作者:无夜之星辰
链接:https://www.jianshu.com/p/0dbe99e914ff

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消