有时候我们想像tableview那样给collectionView添加头部view跟底部view,其实collectionView好像没有想tableview那样有tableHeaderView跟tableFootView(如说的不对,请指正,谢谢),但是有像tableview那样可以添加每组的头部view跟每组的底部view.
下面讲述用xib文件创建headerView
1:首先创建集成 UICollectionReusableView的xib文件.至于要长什么样,自己决定,用xib自动布局.
//初始化CollectionView
- (void)initCollectionView {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//设置headerview,FootView的大小,或者通过下面的代理方法设置
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];
}
代理方法设置headerView FootView
//设置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;
}
}
补充说明 ->适用于多组设置
//执行的 headerView 代理 返回 headerView 的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
CGFloat height = [self.topView getHeight];
return CGSizeMake(320, height);
}
注: 需配合collectionView的使用,实现其必要的代理方法.在这里就不说collectionView的item的设置啦