paul
paul

Reputation: 403

UICollectionView Header and Footer View

I'm using a UICollectionView and need a global header and footer together with section headers. Both global header and footer are supposed to scroll with the rest of the content. Basically they should work exactly like UITableView's tableHeaderView and tableFooterView properties.

diagram

From what I understand supplementary views are either above or below a specific section and decoration views are functionless. My global header and footer are supposed to have interactive elements.

I'm really pulling my hair out after trying for a couple of hours. I found a couple of nasty ways such as hacking around with contentInsets and adding subview to the collectionview. What I'm really looking for is a clean way to do this.

I'm looking forward to any advice!

Upvotes: 30

Views: 11636

Answers (3)

kurryt
kurryt

Reputation: 210

You'll have to create your own custom collection view layout and datasource. The datasource will return global headers and global footers, and section headers and footers, and your custom collection view layout will have to position them accordingly.

THIS IS NOT A VERY SIMPLE PROCESS.

In the WWDC talk Advanced User Interfaces with Collection Views they describe their approach with sample code on how they created a global header. You can use their sample code and then add a global footer section to that.

From Apple:

Advanced User Interfaces with Collection Views

Demonstrates code factoring, swipe to edit, drag reordering, and a sophisticated custom collection view layout.

Upvotes: 6

nikolsky
nikolsky

Reputation: 299

Both Global header and footer are the cells (UICollectionViewCell) of the first and last section

Upvotes: 4

Mathijs
Mathijs

Reputation: 1268

Fix this in the cellForItemAtIndexPath delegate method

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0)
    {
        // first section
    }
else if (indexPath.section == [dataSourceSectionsArray.count]-1)
    {
        // last section
    }
else
    {
        // normal section
    }
}

And you should of course return [dataSourceSectionsArray.count]+2 (one header, one footer) in the numberOfRowsInSection method and keep in mind to always refer to [dataSourceSectionsArray objectAtIndex:indexPath.row-1] when you access your data in a normal cell, since there's no object corresponding to the header in the array.

Upvotes: -4

Related Questions