TableViewDelegateAdDataSource.h:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void(^cellConfigBlock)(UITableViewCell *cell,id item);
@interface TableViewDelegateAdDataSource : NSObject <UITableViewDelegate,UITableViewDataSource>
@property (strong,nonatomic)NSArray *items;
@property (nonatomic,copy)NSString *identfiers;
@property (copy,nonatomic)cellConfigBlock configBlock;
- (instancetype)initWithItems:(id)items
cellIdentifier:(NSString *)cellIdentifier
configBlock:(cellConfigBlock)block;
- (id)indexForTableView:(NSInteger)row;
@end
TableViewDelegateAdDataSource.m:
#import "TableViewDelegateAdDataSource.h"
@implementation TableViewDelegateAdDataSource
- (instancetype)initWithItems:(id)items cellIdentifier:(NSString *)cellIdentifier configBlock:(cellConfigBlock)block{
if (self = [super init]) {
self.items = items;
self.identfiers = cellIdentifier;
self.configBlock = [block copy];
}
return self;
}
- (id)indexForTableView:(NSInteger)row{
return _items[row];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_identfiers];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:_identfiers];
}
id item = [self indexForTableView:indexPath.row];
!self.configBlock ?:self.configBlock(cell,item);
return cell;
}
@end
VC:
#import "ViewController.h"
#import "TableViewDelegateAdDataSource.h"
@interface ViewController ()<UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)TableViewDelegateAdDataSource *obj;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setUpTableView];
}
- (void)setUpTableView{
cellConfigBlock configBlock = ^(UITableViewCell *cell,id item){
cell.textLabel.text = (NSString *)item;
};
self.obj = [[TableViewDelegateAdDataSource alloc]initWithItems:@[@"1",@"2",@"3",@"4",@"5",@"6"] cellIdentifier:@"cellIdentifiers" configBlock:configBlock];
self.tableView.dataSource = self.obj;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
没有对代理方法进行封装,方法都是一样的。
看了网上的博客,自己练练手,..
网友评论