5.7. Providing a Header and a Footer in a Flow Layout


You want to provide header and footer views for your collection view, just as in table views, while using the flow layout.


Follow these steps:

  1. Create a .xib file for your header and another one for your footer.

  2. Drag and drop, from Interface Builder’s Object Library, an instance of Collection Reusable View into your .xib files. Ensure that the collection reusable view that you dropped into your .xib file is the only view in your .xib file. This makes the reusable view the root view of your .xib file, exactly the way that you should provide headers and footers to the collection view.

  3. If you want more control over how your .xib file behaves, create an Objective-C class and associate your .xib file’s root view to your class. This ensures that when your .xib file’s contents are loaded from disk by iOS, the associated class will also be loaded into memory, giving you access to the view hierarchy in the .xib file.

  4. Instantiate the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: instance method of your collection view and register your nib files for the UICollectionElementKindSectionHeader and UICollectionElementKindSectionFooter view kinds.

  5. To customize your header and footer views when they are about to be displayed, implement the collectionView:viewForSupplementaryElementOfKind:atIndexPath: method of your collection view’s data source, and in there, issue the dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: ...

Get iOS 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.