本文以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];
}