How to programmatically add header on UICollectionView with UICollectionViewLayout

cocoa-touch, ios, iphone

Solution

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

Problem

I have a `UICollectionView` in one of my `viewcontroller`. My collection view uses a subclass of `UICollectionViewLayout` (custom) to layout the cells. First thing, as soon as I select Layout as Custom in dropdown on Storyboard, option to select supplementary views goes away. I tried doing that programatically as shown below, but none of the delegate methods are getting called. ``` - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { if (kind == UICollectionElementKindSectionHeader) { UICollectionReusableView *reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; if (reusableview==nil) { reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; } UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; label.text=[NSString stringWithFormat:@"Recipe Group #%li", indexPath.section + 1]; [reusableview addSubview:label]; return reusableview; } return nil; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section { CGSize headerSize = CGSizeMake(320, 44); return headerSize; } ``` In my viewDidLoad Method I have ``` [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"]; ``` Can anyone point me where I'm messing up?

Original source