Introduction to Collection View in IOS | Swift Programming

Saloni Bakshi
The Startup
Published in
4 min readNov 29, 2020

From apple’s documentation, UICollectionView is:

An object that manages an ordered collection of data items and presents them using customizable layouts.

The name and definition makes it clear, it is a way to display a Collection of UI Views in our app. The individual view is referred as a Cell. A common example if photo gallery, displaying images in grid format. In this story, we will see how to setup a basic collection view using storyboard. We can divide this in three sections:

  1. How will my Collection View look?
  2. How can I supply data to the cells?
  3. How to interact with the view cells?

How will my Collection View look?

Let’s add a new UICollectionView. Open the storyboard file in which you want to add the collection view. Press Cmd+Shift+L to open the Xcode Library and search for collection view. Select and drag the Collection View option in your screen. You will see a new blank collection view added on your screen and in left panel under Safe Area.

By default a collection view gets created with a Collection View Cell of type UICollectionViewCell which on expanding has another view called Content View. Content View is the place where we add the content to be displayed for a cell (In photo gallery example, the image thumbnail).

We can configure the Collection View Cell to be of custom class type by subclassing our custom class from UICollectionViewCell. Select the Collection View Cell from left panel of storyboard. On rightmost panel, there is an option to add custom class under identity inspector tab. Also set a reuseIdentifier for the cell under attributes-inspector tab. This will be used to create reusable cell in later sections

The last step is to link the collection view with the ViewController class using IBOutlet properties. Open the storyboard in a new editor tab. Select Collection View in storyboard document view, press option key and drag the pointer to ViewController class. You will see a new property added:

@IBOutlet weak var collectionView: UICollectionView!

How can I supply data to the cells?

The data here refers to any information we want to render the individual cells of collection view (In photo gallery example, the image name or alt text). Here we introduce the dataSource property of UICollectionView.

Before we set the dataSource property, we should know about UICollectionViewDataSource protocol. For any class to be a valid dataSource it should confirm to the UICollectionViewDataSource protocol. What does that mean? To render any data on collection view cells, collection view asks few questions from the dataSource related to number of elements and location. A dataSource must implement these methods to provide required information. We can use a UICollectionViewDiffableDataSource object as your data source object, which already conforms to this protocol. Alternatively, if using a custom class it should confirm to UICollectionViewDataSource protocol by implementing required methods. Let’s now configure our dataSource:

  1. Add UICollectionViewDataSource protocol in ViewController class
class ViewController: UIViewController, UICollectionViewDataSource {
...
}

2. Xcode gives an error on adding line. The error asks you to add the protocol stubs. Click Fix and it will add two methods to your class. The two methods collectionView(_:numberOfItemsInSection:) and collectionView(_:cellForItemAt:) are the required methods for protocol.

3. Implement first method to return the number of items.

func collectionView(_ collectionView: UICollectionView,        numberOfItemsInSection section: Int) -> Int {     // myData is the array of items
return
myData.count
}

4. Implement second method to return the cell to be displayed. You do this by calling the dequeueReusableCell(withReuseIdentifier:for:) method of the collection view and passing the reuse identifier that corresponds to the cell type you want. myCell corresponds to reuseIdentifier identifier set in first section. The CustomCellClass refers to the custom class created for Collection View Cell. If there is no custom class this can be omitted.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {// 
let
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! CustomCellClass
// return cardreturn cell}

5. The last step is to set the dataSource property. In ViewController add below in viewDidLoad().

collectionView.dataSource = self

In this section, we successfully set up the dataSource for our collectionView to the ViewController class. When a collectionView has to render content, it looks into ViewController and get answers from the methods we implemented.

How to interact with the view cells?

Till now, we created a new collection view and passed the data to collection view to create cells. We have a static collection of data. In this section, we will learn how to listen to the user events, like selecting a cell and performing actions on events. It’s time to introduce a new property of UICollectionView, i.e. delegate . The delegate object is responsible for managing selection behaviour and interactions with individual items.

Similar to dataSource, anything to be called as delegate must confirm to a protocol. For delegate the protocol is UICollectionViewDelegate. This protocol exposes number of methods for item selection, highlighting, and performing actions on those items. For this story we will see the didSelectItemAt . Refer here for the complete list. Let’s configure the select item event listener:

  1. Add the protocol UICollectionViewDelegate to the class definition. Since delegate protocol doesn’t have any required methods, it won’t force you to add any stubs.
  2. Set the delegate to ViewController class
collectionView.delegate = self

3. Implement didSelectItemAt : In ViewController class, start typing didSelectItemAt.. and auto-complete feature will help to get the syntax. Press enter, and you get a new function created.

4. The collectionView param is your collection view object and the indexPath refers to the IndexPath of cell selected. To get the cell corresponding to indexPath call cellForItem function.

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {    // add the code here to perform action on the cell
let cell = collectionView.cellForItem(at: indexPath) as? CustomCellClass
}

Thank you, Enjoy learning!!

--

--