有時候我們想像tableview那樣給collectionView添加頭部view跟底部view,其實(shí)collectionView好像沒有想tableview那樣有tableHeaderView跟tableFootView(如說的不對,請指正,謝謝),但是有像tableview那樣可以添加每組的頭部view跟每組的底部view.
下面講述用xib文件創(chuàng)建headerView
1:首先創(chuàng)建集成 UICollectionReusableView的xib文件.至于要長什么樣,自己決定,用xib自動布局.
//初始化CollectionView
- (void)initCollectionView {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//設(shè)置headerview,FootView的大小,或者通過下面的代理方法設(shè)置
flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH*(110/375.0));
flowLayout.footerReferenceSize = CGSizeMake(SCREEN_WIDTH, 60);
_flowLayout = flowLayout;
_s_collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) collectionViewLayout:flowLayout];
_s_collectionview.backgroundColor = [UIColor whiteColor];
_s_collectionview.delegate = self;
_s_collectionview.dataSource = self;
_s_collectionview.showsVerticalScrollIndicator = NO;
//注冊xib
[_s_collectionview registerNib:[UINib nibWithNibName:collectionViewCell bundle:nil] forCellWithReuseIdentifier:collectionViewCell];
[_s_collectionview registerNib:[UINib nibWithNibName:collettionSectionHeader bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collettionSectionHeader];
[_s_collectionview registerNib:[UINib nibWithNibName:collettionSectionFoot bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:collettionSectionFoot];
}
代理方法設(shè)置headerView FootView
//設(shè)置sectionHeader | sectionFoot
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView* view = [_s_collectionview dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collettionSectionHeader forIndexPath:indexPath];
return view;
}else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
UICollectionReusableView* view = [_s_collectionview dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:collettionSectionFoot forIndexPath:indexPath];
return view;
}else{
return nil;
}
}
補(bǔ)充說明 ->適用于多組設(shè)置
//執(zhí)行的 headerView 代理 返回 headerView 的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
CGFloat height = [self.topView getHeight];
return CGSizeMake(320, height);
}
注: 需配合collectionView的使用,實(shí)現(xiàn)其必要的代理方法.在這里就不說collectionView的item的設(shè)置啦