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);
}
网友评论