为UICollectionView的每个section设置footerView和headerView

本文介绍了如何为UICollectionView的每个section设置headerView和footerView。通过创建自定义视图类并注册,遵循UICollectionViewDataSource协议,实现方法来加载视图。其中,`viewForSupplementaryElementOfKind:`区分header和footer,而`estimatedHeightForHeader`和`estimatedHeightForFooter`用于指定尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文以headerView为例。

实现效果如图:

首先学习一下这个类UICollectionReusableView,这个类可以代表headerView和footerView。我们创建UICollectionReusableView这个类的子类来自定义headerView和footerView。

如果要设置headerView和footerView,首先要注册:

    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:UID];

其中,Supplementary翻译成”补充的,额外的”意思。

上面只注册了headerView,接着,实现 UICollectionViewDataSource协议的 collectionView:viewForSupplementaryElementOfKind 方法,并通过这个方法来实现headerView在collection view中显示。
代码如下:

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    UICollectionReusableView* reusableView;

    if (kind==UICollectionElementKindSectionHeader) {
        reusableView=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:UID forIndexPath:indexPath];
    }

    reusableView.backgroundColor=[UIColor orangeColor];

    return reusableView;
}

上面中的kind指定了是headerView还是footerView。
如果是kind==UICollectionElementKindSectionHeader则是headerView,如果是kind==UICollectionElementKindSectionFooter,则是footerView。

记住,一定要为UICollectionReusableView指定尺寸。当然,我们是通过UICollectionView的布局UICollectionViewLayout来制定的。如下面代码:

-(instancetype)init{

    UICollectionViewFlowLayout* flowLayout=[[UICollectionViewFlowLayout alloc] init];

    flowLayout.headerReferenceSize=CGSizeMake(200, 100);

    flowLayout.minimumLineSpacing=10;
    flowLayout.itemSize=CGSizeMake(100, 100);

    return [super initWithCollectionViewLayout:flowLayout];

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值