开发中经常会遇到一个tableView中包含多种样式的cell(如下图),那么在cellForRowAtIndexPath中需要进行ifeles判断,这样会很麻烦,下面介绍一种可以避免这种多重判断的方法
1、创建model基类BaseModel 和子类 OneModel TowModel 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 TowModelCell 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; }
原文地址:https://www.cnblogs.com/chglog/p/10564372.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。