刚刚看了一个关于iOS设计模式的文章,里面提到了tableView代理分离的一种控制器瘦身模式,也可以理解为MVVM模式的一部分,参考点击打开链接。
这里我先简单的将一下这分离过程。
先创建一个代理类
.h文件
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void(^SelectCell)(NSIndexPath * indexPath);
@interface TableViewDelegateObj : NSObject<UITableViewDataSource, UITableViewDelegate>
+(instancetype)createTableViewDelegateWithData:(NSArray *)dataArray SelectBlock:(SelectCell)selectCell;
@end
.m文件
#import "TableViewDelegateObj.h"
@interface TableViewDelegateObj ()
{
NSArray * _dataArray;
SelectCell _selectBlock;
}
@end
@implementation TableViewDelegateObj
+(instancetype)createTableViewDelegateWithData:(NSArray *)dataArray SelectBlock:(SelectCell)selectCell{
return [[[self class] alloc] initTableViewDelegateWithData:dataArray SelectBlock:selectCell];
}
-(instancetype)initTableViewDelegateWithData:(NSArray *)dataArray SelectBlock:(SelectCell)selectCell{
if (self == [super init]) {
_dataArray = dataArray;
_selectBlock = selectCell;
}
return self;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * cellID = @"123";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.textLabel.text = _dataArray[indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_selectBlock(indexPath);
}
控制器中tableview的代码就只需要几行就能搞定,大大减少了控制器中的代码量和tableView的解耦
#import "ViewController.h"
#import "TableViewDelegateObj.h"
@interface ViewController ()
{
UITableView * _tableView;
NSMutableArray * _dataArray;
TableViewDelegateObj * _tableViewDelegate;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self loadLocalData];
[self createTableView];
}
-(void)createTableView{
_tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
_tableViewDelegate = [TableViewDelegateObj createTableViewDelegateWithData:_dataArray SelectBlock:^(NSIndexPath *indexPath) {
NSLog(@"%ld被点击了", (long)indexPath.row);
}];
_tableView.delegate = _tableViewDelegate;
_tableView.dataSource = _tableViewDelegate;
[self.view addSubview:_tableView];
}
-(void)loadLocalData{
_dataArray = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[_dataArray addObject:@"1234"];
}
}
这里只是一个简单的demo,这个方法我觉得比较合适一个控制器有多个tableView,这样只要创建每个tableView对应的代理就可以清晰的区分它们各自代理中的方法,避免多个tableView混淆,使代码更加易读,以后代码或者维护更加方便