技术干货 - tableView多种Cell的选择思路

解决的问题

控制器中不止一种Cell, 我们怎么来设计呢?? 我的实现方法是KeysArr, 那什么是KeysArr呢,我们来看代码.

步骤

  • 1.首先我们需要创建一个全局类 (这个写法和上周的 投机流 自定义转场有异曲同工之妙)

    • 创建全局类全局类中的每一个Key对应着你的一个Cell

.h

extern NSString * const kSQLifestyleBannerKey;
extern NSString * const kSQLifestyleSearchKey;

.m

NSString * const kSQLifestyleBannerKey = @"轮播图";
NSString * const kSQLifestyleSearchKey = @"热点";
  • 2.接着我们创建一个数组来持有这些key; 
    • keys数组
@property (nonatomic,strong) NSArray * keysArr;

- (NSArray *)keysArr {

    if (!_keysArr) {
        _keysArr = @[kSQLifestyleBannerKey,
                    kSQLifestyleSearchKey];
    }
    return _keysArr;
}
  • 3.最后在代理方法中进行判断
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.keysArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString * const key = self.keysArr[indexPath.row];
    if (key == kSQLifestyleBannerKey) {
        SQLifestyleBannerCell * cell = [SQLifestyleBannerCell cellWithTableView:tableView];
        return cell;
    }
    if (key == kSQLifestyleSearchKey) {
        SQLifestyleSearchCell * cell = [SQLifestyleSearchCell cellWithTableView:tableView];
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString * const key = self.keysArr[indexPath.row];
    if (key == kSQLifestyleBannerKey) {
        return [SQLifestyleBannerCell cellHeight];
    }
    if (key == kSQLifestyleSearchKey) {
        return [SQLifestyleSearchCell cellHeight];
    }
    return 0;
}

这样当不需要某个cell显示的时候,只需要将keys从KeysArr中移除即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值