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 theUICollectionElementKindSectionHeaderandUICollectionElementKindSectionFooterview 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: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access