为UICollectionView的每个section设置footerView和headerView

本文以headerView为例。

实现效果如图:

首先学习一下这个类UICollectionReusableView,这个类可以代表headerView和footerView。我们创建UICollectionReusableView这个类的子类来自定义headerView和footerView。

如果要设置headerView和footerView,首先要注册:

    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:UID];

其中,Supplementary翻译成”补充的,额外的”意思。

上面只注册了headerView,接着,实现 UICollectionViewDat

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码添加UICollectionViewheaderView: ``` - (void)viewDidLoad { [super viewDidLoad]; // 初始化UICollectionViewFlowLayout UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; layout.itemSize = CGSizeMake(100, 100); layout.minimumLineSpacing = 10; layout.minimumInteritemSpacing = 10; layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 50); // 初始化UICollectionView UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; collectionView.dataSource = self; collectionView.delegate = self; [self.view addSubview:collectionView]; // 注册UICollectionViewCell [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"]; // 注册UICollectionReusableView [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"]; } #pragma mark - UICollectionViewDataSource - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 10; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; cell.backgroundColor = [UIColor redColor]; return cell; } - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath]; headerView.backgroundColor = [UIColor blueColor]; return headerView; } return nil; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值