灵活式的collectionview的header

来源:互联网 发布:淘宝your highness 编辑:程序博客网 时间:2024/05/21 05:36

今天遇到了这么一个需求,有四个标签栏控制下面一个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);        }
0 0