当前应用都会比较复杂,一个tableView的列表会有多种cell,如果都放在控制器中处理,各种cell利用if,switch判断也会达到效果,但是控制器就会变得很臃肿。其实我们可以利用协议来处理达到效果。并且控制中就很少的代码 1.我们可以创建一个协议文件ModelConfigProtocol.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ModelConfigProtocol <NSObject>
@optional
///获取cell的复用标识
-(NSString *)cellReuseIdentifier;
///获取cell的高度
-(CGFloat)cellHeightWithindexPath:(NSIndexPath*)indexPath;
///点击事件
-(void)cellDidSelectRowAtIndexPath:(NSIndexPath*)indexPath other:(_Nullable id)other;
-(UITableViewCell*)tableView:(UITableView *)tableView reuseIdenyifier:(NSString *)reusedItentifier;
@end
2.创建一个基类模型 BaseModel.h,并且遵守协议,实现协议方法
#import "BaseModel.h"
@implementation BaseModel
- -(NSString *)cellReuseIdentifier {
return @"";
}
-(CGFloat)cellHeightWithindexPath:(NSIndexPath *)indexPath {
return 0.0;
}
-(void)cellDidSelectRowAtIndexPath:(NSIndexPath *)indexPath other:(id)other {
}
-(UITableViewCell*)tableView:(NSString *)tableView reuseIdenyifier:(NSString *)reusedItentifier {
UITableViewCell *cell = [[UITableViewCell alloc]init];
return cell;
}
@end
3.创建一个基类Cell,其余cell继承基类Cell,并且设置遵守协议的模型为其属性 @property(nonatomic,strong)idmodel;
子类Cell重写model的set方法,基类的cell的model的set方法实现一下,不需要做处理,真正处理的是放在子类的cell里,根据具体事务具体分析。
4.控制器中创建cell的时候就可以不用判断来写了
-(void)viewDidLoad {
[super viewDidLoad];
AModel *modelA = [[AModel alloc]init];
BModel *bmodel = [[BModel alloc]init];
CModel *cmodel = [[CModel alloc]init];
DModel *dmodel = [[DModel alloc]init];
self.dataArray = [NSMutableArray array];
[self.dataArray addObject:modelA];
[self.dataArray addObject:bmodel];
[self.dataArray addObject:cmodel];
[self.dataArray addObject:dmodel];
self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.tableView];
self.tableView.tableFooterView = [[UIView alloc]init];
[self.tableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id <ModelConfigProtocol>model = self.dataArray[indexPath.row];
BaseCell *cell = (BaseCell *)[model tableView:tableView reuseIdenyifier:[model cellReuseIdentifier]];
cell.model = model;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
id <ModelConfigProtocol>model = self.dataArray[indexPath.row];
return [model cellHeightWithindexPath:indexPath];
}
oc,swift demo地址 github.com/suifumin/Mo…