IOS之UITableView实现Section独立封装

IOS之UITableView实现Section独立封装

WHY

IOS的UITableView组件,在复杂的场景下,经常会使用多个Section,每个Section都可能有不同的header/cell/footer。如果想对Section的逻辑进行封装,因为delegate和dataSource只能指向单独的实例上,并不是很方便,需要编写一些额外的代码,来分派UITableView的事件。所以完善了上一篇bolg(IOS 实现delegate链/广播的例子),来简化这一工作。

WHAT

CYMTableViewSection @github扩展了UITableView,提供将SectionID对应的事件独立处理的能力。使用此扩展,将很容易对业务层的Section逻辑进行封装。

HOW

以下例子介绍如何使用CYMTableViewSection

  1. 实现两个Section(MySection1和MySection2)

    /** 测试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
    ...
    
  2. 加入UITableView

    
    #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];
    }
  3. 运行,查看结果

依赖

本扩展依赖CYMDelegateChain

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值