美文网首页iOS程序员
UITableviewCell 多种样式处理(运用多态)

UITableviewCell 多种样式处理(运用多态)

作者: mac迷你 | 来源:发表于2018-05-12 18:24 被阅读12次

    demo地址https://github.com/HeartbeatT/CellFactory

     cell在开发中经常需要自定义,多数情况下同一个页面的cell数据类型固定、高度固定。但对于一些页面,cell的样式一样,但是数据类型有多种。我在项目中遇到过一个table里面有11中数据类型。
     ok,其实不管后台返回的list里面有多少种数据类型,肯定会返回一个字段来告诉前端数据类型,这边我们以type字段来表示
    先来看一下json格式:

    [{
        "type": 1,
        "id": 1,
        "name": "qqq"
    }, {
        "type": 2,
        "id": 2,
        "address": "www"
    }]
    

    如此的type会有很多种。在这里我们的唯一不变的就会是type类型和id这两个字段,其余的字段会根据不同的数据类型来改变。
    对于cell类型的判断就需要使用type字段。

    创建model基类

    @property (nonatomic, assign) NSInteger type;
    @property (nonatomic, strong) id    res_info;
    
    
    + (BaseModel *)jsonWithDic:(NSDictionary *)dic;
    
    + (BaseModel *)jsonWithDic:(NSDictionary *)dic
    {
        BaseModel *model = [[self alloc] init];
        model.type = [[dic valueForKey:@"type"] integerValue];
        if (model.type == 1)
        {
            model.res_info = [OneModel jsonWithDic:dic];
        }
        else if (model.type == 2)
        {
            model.res_info = [TwoModel jsonWithDic:dic];
        }
        return model;
    }
    

    这里暂时不需要跳转,我们先忽略id字段。res_info对应的为具体cell数据类型

    model的类型已经搞定,那么怎么需要model与cell类型绑定呢?

    核心就是cellFactory

    创建cellFactory

    #import <Foundation/Foundation.h>
    @class BaseModel;
    
    @interface CellFactory : NSObject
    
    
    
    + (Class)cellWithModel:(BaseModel *)model;
    
    
    @end
    
    
    #import "CellFactory.h"
    #import "BaseModel.h"
    #import "OneModel.h"
    #import "TwoModel.h"
    
    
    #import "OneTableViewCell.h"
    #import "TwoTableViewCell.h"
    
    
    @implementation CellFactory
    
    
    + (Class)cellWithModel:(BaseModel *)model
    {
        Class className = Nil;
        
        if ([model.res_info isKindOfClass:[OneModel class]])
        {
            className = [OneTableViewCell class];
        }
        else if ([model.res_info isKindOfClass:[TwoModel class]])
        {
            className = [TwoTableViewCell class];
        }
        
        
        return className;
    }
    
    
    @end
    
    

    这里我们需要返回的是cell的类型,方便我们结合反射机制与多态

    controller里面这里只写核心代码,详细请看demo

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        BaseModel *model = self.mutableArray[indexPath.row];
        Class className = [CellFactory cellWithModel:model];
        BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(className)];
        return cell;
    }
    

    其实这里cell就是用的多态,来指向子类。
    如果再有新的cell样式加进来,对应的每层业务非常清晰,能够实现快速开发,cellFactory可以实现公用

    相关文章

      网友评论

        本文标题:UITableviewCell 多种样式处理(运用多态)

        本文链接:https://www.haomeiwen.com/subject/zlscdftx.html