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.4. Providing Basic Content to a Collection View

Problem

You have already set up a flow layout for your collection view, but you don’t know how to render cells in your collection view.

Solution

Either use the UICollectionViewCell class directly to present your cells, or subclass this class and provide further implementation on top of that class. In addition, you can have a .xib file associated with your cell, as we will soon see.

Discussion

Note

In this recipe, I assume that you’ve already gone through Recipe 5.3, Recipe 5.2, and Recipe 5.1 and have already set your project up.

Let’s take this one step at a time and start with the fastest and easiest way of creating our cells: instantiate objects of type UICollectionViewCell and feed them to our collection view in our data source. The UICollectionViewCell class has a content view property named contentView, where you can add your own views for display. You can also set various other properties of the cell, such as its background color, which is what we are going to do in this example. But before we begin, let’s first set the expectations of what we are going to achieve in this example code and explain the requirements.

We are going to program a collection view with a flow layout that displays three sections, each of which contains anywhere between 20 and 40 cells, with the first section’s cells all being red, the second section’s cells all being green, and the third section’s cells all being blue, as shown in Figure 5-5.

So let’s get started. ...

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