O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

  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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required