5.7. Providing a Header and a Footer in a Flow Layout
Problem
You want to provide header and footer views for your collection view, just as in table views, while using the flow layout.
Solution
Follow these steps:
Create a .xib file for your header and another one for your footer.
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.
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.
Instantiate the
registerNib:forSupplementaryViewOfKind:withReuseIdentifier:
instance method of your collection view and register your nib files for theUICollectionElementKindSectionHeader
andUICollectionElementKindSectionFooter
view kinds.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 thedequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: ...
Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.