上一篇文章【iOS】如何实现delegate链式或广播调用介绍了如何实现delegate链,同时提供了一个例子,简单的将UITableView的section抽象,使其拥有独立的delegate。这里对这示例进行完善,使其更具备复用性。git
Dispatch delegate to standalone section for UITableView.封装UITableView 的 section, 使section有独立的delegate和dataSource。github
IOS的UITableView组件,在复杂的场景下,常常会使用多个Section,每一个Section均可能有不一样的header/cell/footer。若是想对Section的逻辑进行封装,由于delegate和dataSource只能指向单独的实例上,并非很方便,须要编写一些额外的代码,来分派UITableView的事件。segmentfault
CYMTableViewSection扩展了UITableView,提供将SectionID对应的事件独立处理的能力。使用此扩展,将很容易对业务层的Section逻辑进行封装。测试
如下例子介绍如何使用CYMTableViewSectionspa
实现两个Section(MySection1和MySection2)code
/** 测试section1*/ @interface MySection1 : CYMTableViewSection<UITableViewDataSource> //只需继承自CYMTableViewSection @end @implementation MySection1 -(instancetype)init { self = [super init]; if (self) { self.dataSource = self; } return self; } //处理UITableViewDataSource事件 //只会收到本Section实例对应的SectionId的事件 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellId = @"cellId"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: cellId]; } cell.textLabel.text = [NSString stringWithFormat:@"MySection1 | row %ld",(long)indexPath.row]; return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 3; } @end // 相似方式实现MySection2 ...
加入UITableVieworm
#import "UITableView+CYMSectionAdditions.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //建立两个Section加入tableview MySection1* sec1 = [[MySection1 alloc]init]; MySection2* sec2 = [[MySection2 alloc]init]; [_tabView addSection:sec1 reload:NO]; [_tabView addSection:sec2 reload:NO]; }
运行,查看结果继承
本扩展依赖CYMDelegateChain事件