iOS

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:

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

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

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:

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:

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:

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

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.

Tutorial
RESTful API Tutorial: How to Upload Files to a Server
SwiftUI
Using SwiftData with Preview in SwiftUI
iOS
How to Integrate Your App with Files App in iOS 11
  • MBlue

    MBlueMBlue

    Author Reply

    Good information and easy to follow. Thanks a bunch!


  • Hugh Jeremy

    I would love it if you could post a tutorial with using these as tables cells so that when you press them you can go into a more detailed view, related to the specific item pressed. Thanks !


  • Wouter

    WouterWouter

    Author Reply

    Ooooh, I have another great suggestion for a tutorial, since we already covered working with Core Data and also making a detail view that contains more detail: maybe a way to add your OWN recipe to the list! Including a select menu for the category, and maybe even a way to add a picture to it that you take with your phone? Or is that waaaay beyond our reach yet 🙂

    Anyway, keep it up, these tutorials are SUPER motivating!


  • 乃奇王

    乃奇王乃奇王

    Author Reply

    cool


  • 乃奇王

    乃奇王乃奇王

    Author Reply

    huhu


  • GlasVimle

    GlasVimleGlasVimle

    Author Reply

    Nice tutorial, but you missed to tell we should make files for collectionViewCell and “ctrl drag” the imageView 😉
    Is there any problem to read a Json in to the app? Have not tested yet, are not finished with the last tutorial.

    Thanks for doing this.


    • Gerard

      GerardGerard

      Author Reply

      Have you found a solution? If so, could you point me in its direction? Thanks


  • Andy

    AndyAndy

    Author Reply

    You do realize you’re comparing strings with the ‘==’ operator, right? Don’t do that. This just *happens* to work here because you’re using string constants, but you shouldn’t rely on the pointers being the same. Use “isEqual”.


    • jorge

      jorgejorge

      Author Reply

      actually you should use isEqualToString


  • mike

    mikemike

    Author Reply

    Is there a reason to use this code? The app work without it.

    if (kind == UICollectionElementKindSectionFooter) {
    UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@”FooterView” forIndexPath:indexPath];

    reusableview = footerview;
    }


  • Nic

    NicNic

    Author Reply

    Thanks man. A big tutorial here. I will definitely explore more about UICollectionView


  • Phil Magnuson

    good tutorial, however on my storyboard i cannot create the label as an outlet of the UICollectionReusableView subclass. thoughts? Control drag does not create the outlet.


    • Phil Magnuson

      redid somethings. working now. good tutorial


      • Oput

        OputOput

        Author Reply

        How did you re do it? I’m having an issue of can’t do Control Drag


        • Josh Woods

          Josh WoodsJosh Woods

          Author Reply

          I know this probably way too late, but for people looking at this at this point…I fixed it by making sure the header cell was assigned to the HeaderView custom class. That fixed the problem for me.


  • Shashi

    ShashiShashi

    Author Reply

    Very easy to understand. Thanks


  • Dee

    DeeDee

    Author Reply

    Great… easy to follow… big thanks!


  • Kumar

    KumarKumar

    Author Reply

    Thanks for the tutorial


  • Greg Wang

    Greg WangGreg Wang

    Author Reply

    You need something like the following to get the viewForSupplementaryElementOfKind: being called.

    (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(60.0f, 30.0f);
    }

    (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(60.0f, 30.0f);
    }

    Ref: http://stackoverflow.com/questions/18173191/uicollectionreusableview-method-not-being-called


  • bahri

    bahribahri

    Author Reply

    i downloaded the CollectionViewDemo but İ can not see view in two section and the footer view, when i run the project.Please help me!


    • bahri

      bahribahri

      Author Reply

      Moreover i can not see drinkDesserImages,on the screen


      • bahri

        bahribahri

        Author Reply

        i understanded my mistake.thanks for tutorial


  • Fede Henze

    Fede HenzeFede Henze

    Author Reply

    Nice tutorial!


  • Gerard

    GerardGerard

    Author Reply

    Your tutorial is not working…I have no idea where to find a solution about the fact that “you missed to tell we should make files for collectionViewCell and “ctrl drag” the imageView” as said by GlasVimle.


    • Gerard

      GerardGerard

      Author Reply

      Could you anyone help please? It’s been 3 days I’m on this issue…Thanks


  • Gerard

    GerardGerard

    Author Reply

    How come ”
    Create Grid Layout Using UICollectionView in iOS 6″ works perfectly and as soon as I enter the first lines of code from this page (in the viewDidLoad section), I keep getting the following error message: “return UIApplicationMain(argc, argv, nil, NSStringFromClass([BIDAppDelegate class])); } thread 1 sigabrt”? I checked document versioning as recommended by other forums. I’m on Project SDK (iOS 6.1) and Previous Version (Xcode 4.5). Can you please point me towards a solution? Thx!


    • Gerard

      GerardGerard

      Author Reply

      I get this error when running the app: “2015-01-02 11:25:22.991 RecipePhoto[17718:11303] -[__NSArrayI length]: unrecognized selector sent to instance 0x75619d0”. I read the article hereafter as recommended but still no clue what to do with it…http://codewithchris.com/xcode-errors/#objectlibrary


      • Gerard

        GerardGerard

        Author Reply

        I’m a beginner in iOS…and all I can say this is not a tutorial, let alone for beginners. A tutorial’s objective is to quickly implement what we can learn. Otherwise, it should be rewritten to make sure it works. I’m rather disappointed after having successfully completed more than 10 tutorials for beginners on this site. Then, no more progress in four days and no answers to my messages. Thanks anyway.


  • Gerard

    GerardGerard

    Author Reply

    So I write something about my tech issue, and it gets hidden/deleted by the admin…cool site!


  • ifgs1

    ifgs1ifgs1

    Author Reply

    Great


  • Stack Help

    Stack HelpStack Help

    Author Reply

    what if I delete one section? header view is not deleted if I delete data of one? any solution for that. thanx


  • amy

    amyamy

    Author Reply

    this is an amazing tutorial! is there anyway you can convert it to the recent Xcode/swift


Leave a Reply to Shashi
Cancel Reply

Shares