How to programmatically add header on UICollectionView with UICollectionViewLayout How to programmatically add header on UICollectionView with UICollectionViewLayout ios ios

How to programmatically add header on UICollectionView with UICollectionViewLayout


You're passing in the incorrect view kind.

Your line registering the class:

[self.collectionView registerClass:[UICollectionReusableView class]  forSupplementaryViewOfKind:UICollectionElementKindSectionFooter  withReuseIdentifier:@"HeaderView"];

Should be:

[self.collectionView registerClass:[UICollectionReusableView class]  forSupplementaryViewOfKind: UICollectionElementKindSectionHeader  withReuseIdentifier:@"HeaderView"];

Edit: Looks like your code is all using sectionFooter. Are you trying to programmatically add a header or a footer?


Found the issue, I was not returning attributes of my header in this UICollectionLayoutView method:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; // return an array layout attributes instances for all the views in the given rect


Check that you gave reference size for header in UICollectionViewFlowLayout

[flowLayout setHeaderReferenceSize:CGSizeMake(320, 50)];

and for footer

[flowLayout setFooterReferenceSize:CGSizeMake(320, 50)];