Guido Hendriks Guido Hendriks - 1 year ago 153
Objective-C Question

UICollectionView header not showing

I'm working on a project that uses an

to show several albums. The items show fine, but now I want to show an header above the first section.

To do this, I added the
to my init method. Like this:

[self.collectionView registerNib:[UINib nibWithNibName:@"AlbumHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kAlbumHeaderIdentifier];

Nib contains a view of the class
, which is a subclass of

After that, I implemented

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
return [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kAlbumHeaderIdentifier forIndexPath:indexPath];

Now it should try to load the header view, I suppose. But it doesn't, the method for the supplementary view doesn't get called.

What am I missing? Stuck for hours, have read the documentation on
s many times, but nothing seems to help. Any thoughts?

Answer Source

After looking for the method you asked about, I read that by default the size of headers/footers are 0,0. If the size is 0, the header/footer won't display.

You can set the size with a property:

flowLayout.headerReferenceSize = CGSizeMake(0, 100);

Then all the headers will have the same size. If it has to be different for each section, you can implement the following method, which is part of the UICollectionViewDelegateFlowLayout protocol.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == albumSection) {
        return CGSizeMake(0, 100);

    return CGSizeZero;

Note that in vertical scrolling it uses the returned height and the full width of the collection view, in horizontal scrolling it uses the return width and the full height of the collection view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download