header如果为自定义的UIView 我们创建一个UICollectView支持的ReusableView来作为父容器,将
自定义的header添加进去即可.
@implementation MyCardHeaderReusableView
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self){
[self create];
}
return self;
}
-(void)create
{
//这是我们自定义的header
MyCardHeader *header = [[MyCardHeader alloc] initWithFrame:CGRectZero];
PREPCONSTRAINTS(header);
[self addSubview:header];
ALIGN_TOP(header, 0);
ALIGN_BOTTOM(header, 0);
ALIGN_LEFT(header, 0);
ALIGN_RIGHT(header, 0);
}
@end
//先注册
[self.collectionView registerClass:[MyCardHeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
需要在layout中定义header的尺寸
/**
生成布局
@return UICollectionViewFlowLayout
*/
-(UICollectionViewLayout *)generateCollectFlowLayout
{
//创建瀑布流布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
MyCardHeader *header = [[MyCardHeader alloc] initWithFrame:CGRectZero];
PREPCONSTRAINTS(header);
CONSTRAIN_WIDTH(header, YYScreenSize().width);
CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
//定义header的尺寸
MyCardShopHeader *header = [[MyCardShopHeader alloc] initWithFrame:CGRectZero];
PREPCONSTRAINTS(header);
CONSTRAIN_WIDTH(header, YYScreenSize().width);
CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
layout.headerReferenceSize = CGSizeMake(YYScreenSize().width, height);
layout.minimumLineSpacing = 4;
layout.minimumInteritemSpacing = 4;
layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
return layout;
}
//在delegate返回 `header`
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
MyCardShopHeaderReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
return view;
}