灵活式的collectionview的header

今天遇到了这么一个需求,有四个标签栏控制下面一个collectionview的刷新,其中点到第二个标签的时候需要显示header,照常规办法新建了一个类继承自UICollectionReusableView,然后collectionview注册了一下

[collectionView registerNib:[UINib nibWithNibName:@"EducationHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headID];

然后在collectionview的flowlayout里面设置一下header的尺寸headerReferenceSize = cgsizemake…,然后再数据源方法里面返回header,因为只需要第二个返回,所以加了判断

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (self.categoryView.currentIndex == 2) {
            return [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headID forIndexPath:indexPath];
        }else{
            return nil;
        }
    }
    return nil;
}

运行然后程序崩溃。分析了一下,发现如果不给flowlayout设置header的size,数据源方法都不会走,可能与header的size有关,意思就是你既然给了size,就说明一定是有header,所以就不能返回空。所以就在标签切换的时候控制了一下header的size,问题解决。

        UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)weakSelf.collectionView.collectionViewLayout;
        if (index == 2) {
            layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
            layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 45);
        }else{
            layout.headerReferenceSize = CGSizeZero;
            layout.sectionInset = UIEdgeInsetsMake(20, 15, 0, 15);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值