CollectionView的每個Section也可以自定義Header與Footer醋安,本節(jié)講解如何創(chuàng)建自定義的Header與Footer。
1、創(chuàng)建自定義Header/Footer類(XIB方式)
創(chuàng)建一個自定義類予颤,繼承自:UICollectionReusableView
創(chuàng)建一個xib文件驳庭,并添加一個:Collection Reusable View控件
定義樣式
2氯窍、注冊Header與Footer
分別添加Header與Footer的可重用標(biāo)示符
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、實現(xiàn)Header與Footer的數(shù)據(jù)源方法
實現(xiàn)CollectionView的viewForSupplementaryElementOfKind:代理方法执泰,并設(shè)置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试幽、設(shè)置Header與Footer的大小
實現(xiàn)UICollectionViewDelegateFlowLayout協(xié)議中的referenceSizeForHeaderInSection以及referenceSizeForFooterInSection方法,設(shè)置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);
}