转载自汪海的实验室
一 定义dataSource
dataSource.h
- typedef void (^TableViewCellConfigureBlock)(id cell, id item);
- @interface GroupNotificationDataSource : NSObject<UITableViewDataSource>
- - (id)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;
- - (id)itemAtIndexPath:(NSIndexPath *)indexPath;
- @end
dataSource.m
- @implementation GroupNotificationDataSource
- {
- NSArray *_itemsArray;
- NSString *_cellIdentifier;
- TableViewCellConfigureBlock _configureCellBlock;
- }
- - (id)init{
- return nil;
- }
- - (id)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock{
- self = [super init];
- if (self) {
- _itemsArray = anItems;
- _cellIdentifier = aCellIdentifier;
- _configureCellBlock = [aConfigureCellBlock copy];
- }
- return self;
- }
- - (id)itemAtIndexPath:(NSIndexPath *)indexPath {
- return _itemsArray[(NSUInteger) indexPath.row];
- }
- #pragma mark tableView DataSource
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
- return _itemsArray.count;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
- // NOTE: This method can return nil so you need to account for that in code
- GroupNotificationCell *cell=[tableView dequeueReusableCellWithIdentifier:_cellIdentifier];
- // NOTE: Add some code like this to create a new cell if there are none to reuse
- if (cell==nil) {
- cell=[[GroupNotificationCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_cellIdentifier];
- }
- id item = [self itemAtIndexPath:indexPath];
- _configureCellBlock(cell, item);
- return cell;
- }
其中,需要注意tableView:cellForRowAtIndexPath:方法中对于cell的重用
二 重写cell的初始化
cell.h
- - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
cell.m
- - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
- self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
- if (self) {
- [self configureUI];
- }
- return self;
- }
三 controller中设置tableview的dataSource
- _dataSource=[[GroupNotificationDataSource alloc]initWithItems:[NSArray arrayWithObjects:@"1",@"2", nil nil] cellIdentifier:CellIdentifier configureCellBlock:^(id cell, id item) {
- //
- }];
- _tableview.dataSource=_dataSource;
需要注意的是_dataSource应该是成员变量,而非局部变量,否则会报错:message send to delloced object