iOS之Cell工厂解决多种cell的困扰

在开发过程中经常遇到tabView中包含多种样式的cell,这里介绍一种cell工厂模式 

下面示例中含有示图的三种cell



iOS之Cell工厂解决多种cell的困扰_第1张图片


1. 创建model基类BaseModel   和子类 OneModel   TwoModel   ThreeModel

     在BaseModel 中 创建对应model

   

+ (instancetype)initWithDictionary:(NSDictionary *)dictionary;


根据字典内提供的数据分别创建出其对应的model来获取数据

+ (instancetype)initWithDictionary:(NSDictionary *)dictionary {

    先使用当前类(父类)创建出model对象

    BaseModel *model = nil;


    根据字典中key对应的数据初始化不同的子类对象并将其返回给我们的父类

    if ([dictionary[@"tag"]isEqualToString:@"Top News"]) {


        model = [[OneModel alloc]init];


    }else if ([dictionary[@"tag"]isEqualToString:@"imgextra"]) {


        model = [[TwoModel alloc]init];


    }else if ([dictionary[@"tag"]isEqualToString:@"music"]) {


        model = [[ThreeModel alloc]init];

    }

    

    [model setValuesForKeysWithDictionary:dictionary];

    return model;

}


//保护方法

-(void)setValue:(id)value forUndefinedKey:(NSString *)key {

    

}



2. 在viewDidLoad获取数据

  self.dataArr = [[NSMutableArray alloc]init];

    //根据文件路径获取数据

    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];

    //使用字典遍历数组内的所有数据

    for (NSDictionary *dict in array) {

        BaseModel *model = [BaseModel initWithDictionary:dict];

        //将不同子类创建出的model对象添加到我们的数组当中

        [self.dataArr addObject:model];

    }


3. cell基类BaseModelCell  和子类OneModelCell   TwoModelCell   ThreeModelCell  (注意cell的名字和model的关联,下面要使用)  

根据不同类型的model创建出不同的cell

+ (instancetype)initWithModel:(BaseModel *)model;

+ (instancetype)initWithModel:(BaseModel *)model

{

    //根据我们的OC函数获取我们的model类名并将其转化为OC字符串

    NSString *modelName = [NSString stringWithUTF8String:object_getClassName(model)];

    //使用model的类名拼接一个"Cell"来获取到我们的Cell类名

    NSString *cellName = [modelName stringByAppendingString:@"Cell"];

    //根据我们所提供的cellName来获取其对应的“cell子类初始化一个cell对象返回给我们的父类对象

    //唯一标识符可以使用我们所提供的model来给予不同cell所对应的标识来重用。

    BaseTableViewCell *cell = [[NSClassFromString(cellName) alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:modelName];

    

    return cell;

}


同时, 在父类中声明出一个BaseModel对象,在其子类里重写set方法,在set方法内部去做赋值的操作  在子类完成对应视图布局

@property (nonatomic, strong) BaseModel *baseModel;


注意:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //根据我们的indexPath.row获取我们对应的model

    BaseModel *baseModel = [self.dataArr objectAtIndex:indexPath.row];

    //根据取出来的model获取其对应的类名

    NSString *modelName = [NSString stringWithUTF8String:object_getClassName(baseModel)];

    //根据不同的唯一标示重用不同的cell

    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:modelName];

    //如果我们的cell不存在

    if (cell == nil) {

        //根据我们每行提供的model创建出对应的cell

        //根据不同需求生产不同的产品

        cell = [BaseTableViewCell initWithModel:baseModel];

    }

    

    [cell setBaseModel:baseModel];

    

    return cell;

}





你可能感兴趣的:(iOS开发)