UICollectionView详解:6-补充视图(Header/Footer)

CollectionView的每个Section也可以自定义Header与Footer,本节讲解如何创建自定义的Header与Footer。

1、创建自定义Header/Footer类(XIB方式)

创建一个自定义类,继承自:UICollectionReusableView

创建一个xib文件,并添加一个:Collection Reusable View控件

定义样式

2、注册Header与Footer

分别添加Header与Footer的可重用标示符

staticNSString*constreuseIdentifierHeader=@"MYHeaderCell";

staticNSString*constreuseIdentifierFooter=@"MYFooterCell";

在viewDidLoad方法中注册Header与Footer

[self.collectionView registerNib:[UINibnibWithNibName:@"MYHeaderView"bundle:nil]forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:reuseIdentifierHeader];

[self.collectionView registerNib:[UINibnibWithNibName:@"MYFooterView"bundle:nil]forSupplementaryViewOfKind:UICollectionElementKindSectionFooterwithReuseIdentifier:reuseIdentifierFooter];

3、实现Header与Footer的数据源方法

实现CollectionView的viewForSupplementaryElementOfKind:代理方法,并设置Header、Footer的一些属性,如下:

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

UICollectionReusableView*supplementaryView;

if([kind isEqualToString:UICollectionElementKindSectionHeader]){

MYHeaderView*view=(MYHeaderView*)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:reuseIdentifierHeader forIndexPath:indexPath];

view.headerLabel.text=[NSStringstringWithFormat:@"这是header:%d",indexPath.section];

supplementaryView=view;

}

elseif([kind isEqualToString:UICollectionElementKindSectionFooter]){

MYFooterView*view=(MYFooterView*)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooterwithReuseIdentifier:reuseIdentifierFooter forIndexPath:indexPath];

view.footerLabel.text=[NSStringstringWithFormat:@"这是Footer:%d",indexPath.section];

supplementaryView=view;

}

returnsupplementaryView;

}

4、设置Header与Footer的大小

实现UICollectionViewDelegateFlowLayout协议中的referenceSizeForHeaderInSection以及referenceSizeForFooterInSection方法,设置Header与Footer的大小

-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

CGFloatscreenWidth=[UIScreenmainScreen].bounds.size.width;

returnCGSizeMake(screenWidth,69);

}

-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{

CGFloatscreenWidth=[UIScreenmainScreen].bounds.size.width;

returnCGSizeMake(screenWidth,50);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容