Skip to main content

How to Add Header and Footer View in UICollectionView

Header and Footer View in UICollectionView

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.

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

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];
}

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

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. we’ve added space between the sections.

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

Go back to Storyboard. Select “Collection View” of the Collection View controller. In Attributes inspector, select both “Section Header” and “Section Footer” for Accessories.

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.

                             
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.

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

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

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

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, we use the identifier that we’ve assigned earlier to get the header/footer view.


Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...