UICollectionView添加头视图

UICollectionView与UITableView一样都需要遵从代理和数据源的方法。

1.UICollectionView 创建之前需要先写布局,每个collection都需要遵从这个布局。

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

CGFloat itemW = kScreenWidth/3;

CGFloat itemH = 0.85*itemW + 20;

layout.itemSize = CGSizeMake(itemW, itemH);

layout.headerReferenceSize = CGSizeMake(0, 10); //头视图的大小参数

layout.minimumInteritemSpacing = 0;

layout.minimumLineSpacing = 0; // cell 间距


2.然后注册头视图

[_collection registerClass:[UICollectionReusableViewclass] forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:@"header"];

3.代理方法

//创建collection头视图

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{

UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];

header.backgroundColor = ZJColorFromRGB(0xf6f6f6);

return header;

}

// 设置section头视图的参考大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

{

return CGSizeMake(kScreenWidth, 10);

}

如果需要自定义头视图实现具体功能,可以继承UICollectionReusableView来实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容