iOS Programming · · 7 min read

How to Add Header and Footer View in UICollectionView

How to Add Header and Footer View in UICollectionView

Previously, we covered the basics of UICollectionView and showed you how to present items in grid layout. It’ll be interesting to spilt recipes into different sections. Let’s say, the first section contains recipes for lunch/dinner, while the other section contains recipes for drinks and desserts.

As you’ve learnt, every collection view must have a data source object providing it with content to display. Its responsibility is to provide the collection views with the following:

  • The number of sections in the collection view
  • The number of items in each section
  • The cell view for a particular data item

Obviously, the simple Recipe app we developed in the previous tutorial contains one section only. In this tutorial, we’ll continue to explore collection view and show you how to group the items into different sections. You’ll also learn how to add header or footer view to the collection view.

If you haven’t read the first tutorial, I encourage to check it out first. Otherwise, you can get started by downloading the full source from here.

Split Recipes into Two Sections in UICollectionView

In the simple Recipe app, the RecipeCollectionViewController is the data source object of the collection view. In order to split the recipes into two sections, there are a number of changes we have to implement.

Originally, the recipeImages array stores the image names for all recipes. As we’d like to split the recipes into two groups, we’ll modify our code and use nested arrays to store different groups of recipes. The term nested arrays may be new to some of you if you do not have much programming experience. The below figure depicts how we use nested arrays to store the data. The first group contains images of main dish, while the other one represents images of drink and dessert. The top-level array (i.e. recipeImages) contains two arrays representing the sections. For each section array, it contains the date items (i.e. image name of recipe) for that particular section.

Nested Array Explained

Nested Array Explained

Let’s go back to the source code. In the RecipeCollectionViewController.m, change the initialization of “recipeImages” array under viewDidLoad method to the following:

- (void)viewDidLoad
    [super viewDidLoad];
    // Initialize recipe image array
    NSArray *mainDishImages = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"full_breakfast.jpg", @"ham_and_cheese_panini.jpg", @"ham_and_egg_sandwich.jpg", @"hamburger.jpg", @"instant_noodle_with_egg.jpg", @"japanese_noodle_with_pork.jpg", @"mushroom_risotto.jpg", @"noodle_with_bbq_pork.jpg", @"thai_shrimp_cake.jpg", @"vegetable_curry.jpg", nil];
    NSArray *drinkDessertImages = [NSArray arrayWithObjects:@"angry_birds_cake.jpg", @"creme_brelee.jpg", @"green_tea.jpg", @"starbucks_coffee.jpg", @"white_chocolate_donut.jpg", nil];
    recipeImages = [NSArray arrayWithObjects:mainDishImages, drinkDessertImages, nil];


The above code splits the recipe images into two groups. Next, modify the “numberOfItemsInSection:” method to return the number of items in each section:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [[recipeImages objectAtIndex:section] count];

Next, modify the “cellForItemAtIndexPath:” method to the following:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    RecipeViewCell *cell = (RecipeViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame-2.png"]];
    return cell;

If you compare the code with the one we implemented previously, line #7 is the only change. We first retrieve the array by using the section number and then get the specific items from the section.

Lastly, we have to tell the collection view that we have two sections. This can be done by implementing a method called numberOfSectionsInCollectionView: in RecipeCollectionViewController.m, which returns the total number of section in the collection view:

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
    return [recipeImages count];

Now compile and run the app, you should now have a screen similar to the following:

Recipe App with Two Sections

Recipe App with Two Sections

Tweak the Margin of Your Content using Section Insets

The app works but it doesn’t look good. The last row of images in the first section is too close to the first row of the second section. You can use section insets to add space around the side of the content. The below figure demonstrates how insets affect the content:

Add margin using section insets

Add margin using section insets

You can use UIEdgeInsetsMake to create an inset:

inset = UIEdgeInsetsMake(top, left, bottom, right);

For our Recipe app, we only want to add space between sections. In the viewDidLoad method of RecipeCollectionViewController.m, add the following code:

    UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    collectionViewLayout.sectionInset = UIEdgeInsetsMake(20, 0, 20, 0);

The above code creates and assigns the insets to the collection view. Now compile and run the app again. As you can see from the below screenshot, we’ve added space between the sections.

Recipe Collection View with Insets

Recipe Collection Views with Insets

Adding Header and Footer Views

Now let’s further tweak the app to make it even cooler. We’ll add header and footer views for each section of recipes. The UICollectionViewFlowLayout, that our app is using, already provides optional header and footer views for each section. Here the header and footer views can be referred as the supplementary views of the flow layout. By default, these views are disabled in the flow layout. There are a couple of things to configure the header/footer view:

  1. Enable the section header/footer view in Storyboard (We try to keep thing simple. It’s not a must to enable the header/footer through Storyboard. Programmatically you can do this by implementing the appropriate delegate methods or by assigning appropriate values to the headerReferenceSize and footerReferenceSize properties.)
  2. Implement collectionView:viewForSupplementaryElementOfKind method as required by UICollectionViewDataSource protocol. By implementing the method, you provide a supplementary view to display in the collection view.

Designing Section Header/Footer in Storyboard

First, download the header/footer background images and add them into the Xcode project.

Go back to Storyboard. Select “Collection View” of the Collection View controller. In Attributes inspector, select both “Section Header” and “Section Footer” for Accessories. Once enabled, you should see the header and footer views appeared on screen.

Storyboard Enables Section Header and Footer

Enables section header and footer in Storyboard

Both header and footer views are blank by default. We’re going to design the views using Storyboard. The header view is designed to display a section title, while the footer view only shows a static banner image. In Storyboard, drag an image view from Object Library to the header view and add a label on top of it. Set the font colour to white. For the footer, simply add an image view.

Design header and footer views

Designing header and footer views

Select the image view of the footer view, assign the “footer_banner.png” as the background image in the Attributes inspector.

Add Footer View Background

Assign background image for the footer view

Most importantly, we have to assign an identifier for the header and footer view. The identifier will be used in code for identifying the view. Select the Collection Reusable View of the header, set the identifier as “HeaderView” in the Attributes inspector. For the Collection Reusable View of the footer, set the identifier as “FooterView”.

Collection Reusable View Header Identifier

Assigning identifier for header/footer view

New Class for Header View

By default, both header and footer views are associated with the UICollectionReusableView class. To display our own background image and title in the header view, we have to create a custom class which is a subclass of UICollectionReusableView. Let’s name the new class as “RecipeCollectionHeaderView”.

Add Collection Header View Class

Create a new class for header view

In Storyboard, select the Collection Reusable View of the header, set the custom class as “RecipeCollectionHeaderView” in Identify inspector. Press and hold the control key, click the image view in the header and drag it towards the RecipeCollectionHeaderView.h to insert an Outlet variable. Name the variable as “backgroundImage”. Repeat the same procedure for the UILabel and name the variable as “title”.

Establish connection with RecipeCollectionHeaderVeiw

Establish connection with RecipeCollectionHeaderView class

Implementing viewForSupplementaryElementOfKind Method

If you try to build and run the app, you will not see the header and footer as we haven’t implemented the “viewForSupplementaryElementOfKind:” method. Select the “RecipeCollectionViewController” and add the import statement statement:

#import "RecipeCollectionHeaderView.h"

Then implement the viewForSupplementaryElementOfKind: method by using the following code:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        RecipeCollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        NSString *title = [[NSString alloc]initWithFormat:@"Recipe Group #%i", indexPath.section + 1];
        headerView.title.text = title;
        UIImage *headerImage = [UIImage imageNamed:@"header_banner.png"];
        headerView.backgroundImage.image = headerImage;
        reusableview = headerView;
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];

        reusableview = footerview;
    return reusableview;

The above code tells the collection view which header/footer view should be used in each section. We first determine if the collection view asks for a header or footer view. This can be done by using the kind variable. For header view, we dequeue the header view (by using dequeueReusableSupplementaryViewOfKind: method) and set an appropriate title and image. As you can see from line 6 and 16 of the code, we use the identifier that we’ve assigned earlier to get the header/footer view.

Now compile and run the app again. Your app should display the header and footer in each section.

Recipe App with Header and Footer

Recipe App with Header and Footer

What’s Coming Next?

I hope you enjoy the tutorial. We’ve gone through the basics of supplementary views and showed you how to add header/footer in collection view. In the next tutorial, we’ll continue to discuss collection view and show you how to interact with the collection cell. (Update: The third tutorial article about collection view is now available.)

For your complete reference, you can download the full source code of the Xcode project here. But make sure you use Xcode 4.5 (or up) to compile it.

As always, feel free to leave us comment to share your question and suggestions.

Read next