iOS UICollectionView 添加header footer

  1. 注册头部和底部视图
  [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeViewCollectionViewHeader"];
  [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"HomeViewCollectionViewFooter"];

2.头部视图和底部视图的大小

 UICollectionViewFlowLayout *_customLayout = [[UICollectionViewFlowLayout alloc] init]; // 自定义的布局对象
    _customLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
 //设置headerView大小
  _customLayout.headerReferenceSize = CGSizeMake(KScreenWidth, KWidth(560)); 
//设置footerView大小
 _customLayout.footerReferenceSize = CGSizeMake(KScreenWidth, KWidth(560));  
  1. 设置内容
#pragma mark - 视图内容
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    // 视图添加到 UICollectionReusableView 创建的对象中
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HomeViewCollectionViewHeader forIndexPath:indexPath];
        return headerView;

    }else if (kind == UICollectionElementKindSectionFooter) {
        // 底部试图
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HomeViewCollectionViewFooter forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor redColor];
        return headerView;
        
    }else {
        return nil;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。