viewController 瘦身 -- 通过新建DataSource类来管理tableView的数据源方法
大致思路: 新建一个DataSource类,把tableView 的数据源代理交给这个类。
核心代码:
ViewController中:
- (void)setupTableView {
// 创建回调,用于在数据源方法中,对cell进行处理
TableViewCellConfigureBlock configureBlock = ^(TestCell *cell, model *item) {
[cell configureWithModel:item];
};
// 创建dataSource类,同时把需要用到的数据,cellId, 回调传进去
self.dataSource = [[ArrayDataSource alloc] initWithItems:self.modelArr cellIdentifier:CellId configureCellBlock:configureBlock];
// 设置数据源代理
self.mainTable.dataSource = self.dataSource;
}
新建的ArrayDataSource类:
- (instancetype)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureBlock {
if (self = [super init]) {
self.itmes = anItems;
self.cellIdentifier = aCellIdentifier;
self.configureBlock = aConfigureBlock;
}
return self;
}
// 数据源代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.itmes.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier];
id item = self.itmes[indexPath.row];
self.configureBlock(cell, item);
return cell;
}
Cell 处理方法
- (void)configureWithModel:(model *)m {
self.titleLabel.text = m.title;
self.descLabel.text = m.desc;
}
Github 上的实例项目

浙公网安备 33010602011771号