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

被折叠的 条评论
为什么被折叠?



