分离tableview的datasource , 实现ViewController “瘦身”
这是一个实现轻量级ViewController的基本方法,大家通过这个代码页可以实现代理的分离.
#import <Foundation/Foundation.h>
typedef void(^TableViewCellConfigureBlock) (id cell,id item);
@interface ZYYArrayDataSource : NSObject<UITableViewDataSource>
-(id)initWithItems:(NSArray *)anItems cellItentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConofigureCellBlock;
- (id)itemAtIndexPath:(NSIndexPath *)indexPath;
@end
#import "ZYYArrayDataSource.h"
#import "ZYYDataCell.h"
@interface ZYYArrayDataSource()
@property (nonatomic, strong) NSArray *items;
@property (nonatomic, copy) NSString *cellIdentifier;
@property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock;
@end
@implementation ZYYArrayDataSource
- (id)init
{
return nil;
}
-(id)initWithItems:(NSArray *)anItems cellItentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConofigureCellBlock
{
self = [super init];
if (self) {
self.items = anItems;
self.cellIdentifier = aCellIdentifier;
self.configureCellBlock = [aConofigureCellBlock copy];
}
return self;
}
-(id)itemAtIndexPath:(NSIndexPath *)indexPath
{
return self.items[(NSUInteger)indexPath.row];
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ZYYDataCell * cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier];
if (cell== nil) {
cell = [[ZYYDataCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.cellIdentifier];
}
id item = [self itemAtIndexPath:indexPath];
self.configureCellBlock(cell,item);
return cell;
}
@end
//在viewController里面这么使用就可以了
UITableView * tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.mTableView = tableView;
//为初始化列表的数据源声明一个block
TableViewCellConfigureBlock configureBlock = ^(ZYYDataCell *cell,NSString * titile){
[cell configureForData:titile];
};
//初始化列表的数据源
_dataSource = [[ZYYArrayDataSource alloc]initWithItems:self.mArrayData cellItentifier:@"ID" configureCellBlock:configureBlock];
self.mTableView.dataSource = _dataSource;
//把列表添加到View上
[self.view addSubview:self.mTableView];