1、基于NSObject封装TableView
TableViewDelegateObj.h
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> typedef void (^selectCell) (NSIndexPath *indexPath); /** * 代理对象(UITableView的协议需要声明在.h文件中,不然外界在使用的时候会报黄色警告,看起来不太舒服) */ @interface TableViewDelegateObj : NSObject <UITableViewDelegate, UITableViewDataSource> /** * 创建代理对象实例,并将数据列表传进去 * 代理对象将消息传递出去,是通过block的方式向外传递消息的 * @return 返回实例对象 */ + (instancetype)createTableViewDelegateWithDataList:(NSArray *)dataList selectBlock:(selectCell)selectBlock; @end
TableViewDelegateObj.m
#import "TableViewDelegateObj.h" @interface TableViewDelegateObj () @property (nonatomic, strong) NSMutableArray *dataList; @property (nonatomic, copy) selectCell selectBlock; @end @implementation TableViewDelegateObj + (instancetype)createTableViewDelegateWithDataList:(NSMutableArray *)dataList selectBlock:(selectCell)selectBlock { return [[[self class] alloc] initTableViewDelegateWithDataList:dataList selectBlock:selectBlock]; } - (instancetype)initTableViewDelegateWithDataList:(NSMutableArray *)dataList selectBlock:(selectCell)selectBlock { self = [super init]; if (self) { self.dataList = dataList; self.selectBlock = selectBlock; } return self; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; } cell.textLabel.text = self.dataList[indexPath.row]; return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dataList.count; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:NO]; // 将点击事件通过block的方式传递出去 self.selectBlock(indexPath); }
2、 Controller调用
#import "ViewController.h" #import "TableViewDelegateObj.h" @interface ViewController () @property (strong, nonatomic) NSMutableArray * arr_test; @property (strong, nonatomic) TableViewDelegateObj * tbd_obj; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.arr_test = [NSMutableArray arrayWithObjects:@"索马里猫",@"土耳其梵猫",@"美国短毛猫", nil]; self.tbd_obj = [TableViewDelegateObj createTableViewDelegateWithDataList:self.arr_test selectBlock:^(NSIndexPath *indexPath) { NSLog(@"第%@行",indexPath); }]; self.tb_test.delegate = self.tbd_obj; self.tb_test.dataSource = self.tbd_obj; //增加延时看下效果 [self performSelector:@selector(reloadDataFromNewREquest) withObject:nil afterDelay:2.0]; } - (void)reloadDataFromNewREquest { [self.arr_test addObject:@"非洲薮猫"]; [self.tb_test reloadData]; } - (NSMutableArray *)arr_test { if (!_arr_test) { _arr_test = [[NSMutableArray alloc]init]; } return _arr_test; }
参考地址:http://www.cocoachina.com/ios/20160317/15696.html