项目中需求时三个区,没个区展示不同的数据,一格一格的,所以tableView是不是适用的,需要采用collectionView才能更好的展示,那么怎么给它添加区头区尾呢?
第一步:需要先注册区头区尾
// 注册区头
[_collectionView registerClass:[CNCollectionReusableHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
// 注册区尾
[_collectionView registerClass:[CNCollectionReusableFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier];
第二步:实现代理方法,返回区头区尾的尺寸
// 设置区头尺寸高度
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
CGSize size = CGSizeMake(SCREEN_WIDTH, 60);
return size;
}
// 设置区尾尺寸高度
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
CGSize size = CGSizeMake(SCREEN_WIDTH, 1);
return size;
}
第三步:设置区头view和区尾view
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
UICollectionReusableView *reusableView = nil;
// 区头
if (kind == UICollectionElementKindSectionHeader) {
CNCollectionReusableHeaderView *headerView = (CNCollectionReusableHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
headerView.titleLab.text = _titleArray[indexPath.section];
reusableView = headerView;
}
// 区尾
if (kind == UICollectionElementKindSectionFooter) {
CNCollectionReusableFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier forIndexPath:indexPath];
reusableView = footerView;
}
return reusableView;
}
这样就可以实现在collectionView上添加区头和区尾。大家可以看到我的区头和区尾用的继承自 UICollectionReusableView
的 CNCollectionReusableHeaderView
和 CNCollectionReusableFooterView
,这样写的目的是为防止刷新collectionView时区头和区尾重复添加,这一点是需要注意的。