XZ_iOS之collectionView的header和footer的重用

效果图如下,每一个section的头视图是一个label
代码如下:
// 1.创建collectionView
UICollectionViewFlowLayout*flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize= CGSizeMake(W / 2.0 - 1,40);
    flowLayout.
minimumInteritemSpacing= 1;
    flowLayout.
minimumLineSpacing= 2;
   
// 设置section的头标题大小
    flowLayout.
headerReferenceSize= CGSizeMake(W,40);
//    flowLayout.footerReferenceSize = CGSizeMake(W, 100);
   
self.categoryCV= [[UICollectionViewalloc]initWithFrame:[UIScreenmainScreen].boundscollectionViewLayout:flowLayout];
   self.categoryCV.backgroundColor= [UIColorcolorWithWhite:240/255.0alpha:1];
    [self.viewaddSubview:self.categoryCV];
// 2.创建一个可重用的section的头视图,继承自UICollectionReusableView
XZCategoryCollectionHeaderView.h中
@interfaceXZCategoryCollectionHeaderView : UICollectionReusableView
@property(nonatomic,strong)UILabel *title;
@end
XZCategoryCollectionHeaderView.m中
self.title= [[UILabelalloc]initWithFrame:CGRectMake(15,0,self.bounds.size.width,self.bounds.size.height)];
[selfaddSubview:self.title];
// 3.在controller中注册
staticNSString *headerReuseID = @"collection_header";
//注册UICollectionReusableViewheaderView
    [self.categoryView.categoryCVregisterClass:[XZCategoryCollectionHeaderViewclass]forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:headerReuseID];
// 3.在代理方法中调用
#pragma mark - UICollectionViewDelegateFlowLayout
//设置section的头标题
- (
UICollectionReusableView*)collectionView:(UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath{
   
UICollectionReusableView *reuseableView = nil;
   
// 如果是section的头
   
if (kind == UICollectionElementKindSectionHeader) {
       
XZCategoryCollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:headerReuseIDforIndexPath:indexPath];
       
NSString *title = self.categoryArr[indexPath.section][@"sTitle"];
        headerView.
title.text= title;
        reuseableView = headerView;
    }
   return reuseableView;
}

// 代码部分只是头视图的代码,footer的使用规则一样
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值