Get started with UICollectionView 🍏

Irem Karaoglu
8 min readDec 28, 2022

--

Photo by Nathana Rebouças on Unsplash

There is a common thing in the apps we use in our daily routine: a list on a screen. It’s sometimes a list of restaurants, songs, posts, and so on. Therefore, learning UITableView or UICollectionView (which are the classes you may use to achieve a list on a screen) are essential if you are an iOS developer. In this article, I am going to cover UICollectionView for the iOS development beginners.

UICollectionView is a class in the UIKit framework that provides a way to display and manage a collection of data items in a grid-like layout. It is introduced in iOS 6. It is commonly used in iOS applications to display items such as images in a gallery or contacts in a list. UICollectionView provides a flexible and customizable way to present data to the user, and it is an essential tool for many iOS developers.

UITableView vs UICollectionView

They are both data bound controllers and offer a list on a screen but they differentiate at some points.

  • Table View does not support multiple columns side by side, but Collection View does.
  • Table View does not support horizontal scrolling, only vertical scrolling is supported. On the other hand, Collection View supports scrolling in both directions.
  • Table View does not support customization as much as Collection View does. In Collection View your list elements does not have to be in the same style, they may differentiate.

Here are some examples for horizontal and vertical scrolling.

Horizontal Scrolling

Vertical Scrolling

Now it’s time to develop a demo application to understand better. In the process of this tutorial, you will learn:

  • having CollectionView in a screen
  • reusing Collection View cells
  • UICollectionViewFlowLayout

Tutorial

1- Create an Xcode project with Storyboard.

2- Open main.storyboard file and add a UICollectionView component to the canvas.

adding UICollectionView to canvas

3- Now, set the collection view constraints to make it cover the whole screen.

Set 0 as constraints for all directions.

setting constraints

4- Next, you need to set a reuse identifier for a cell.

Under the build-time warnings tab, you will see “Prototype collection view cells must have reuse identifiers”. You may easily set an identifier under the Attributes Inspector.

setting reuse identifier for cell

Here, cell is used for each item on the list. How about reusing identifier? We will cover it later on, keep reading.

5- Now, set some data to show on the screen and implement data source class which is called UICollectionViewDataSource.

I preferred to set an array of colors to show on the screen as a list. I added below code snippet inside of ViewController class.

Then, it’s time to implement UICollectionViewDataSource and create the necessary functions.

Add the following extension to ViewController file.

These functions provide:

  • How many items you want to show in that collection view section (by default it’s one section — we will discuss sections later on)
  • Which cell you want to show

Now, it will give you some errors. Don’t worry, we will fix them in following steps.

6- Connect IBOutlet to ViewController and assign data source delegate to self in viewDidLoad function as “collectionView.dataSource = self”.

While connecting IBOutlet to ViewController; you may click CollectionView, click control button and drag & drop to ViewController.

7- Let’s fill the data source functions and get rid of the errors.

For the counts of the items we would like to show -> We may set as the count of our color array since we’d like to show all of the items in our data source.

For the which cell we would like to show -> We may set as “cell” (⚠️ this has to be the same name with the identifier that we previously set in Step 4.)

⚠️ Don’t forget that, if you will have different types of Collection View cells in a screen, having more specific and meaningful names rather than “cell” would be beneficial for you. e.g “productCell”, “horizontalCell”

Let’s go back to our function, I set background color from colorData array and returned the cell.

We use “dequeue reusable cell with reuse identifier” terminology at this step, but what does it mean? Now, it’s time to talk about that.

Dequeueing means removing something from a sequence of items.

Reusing collection view cells

Let’s say we have a huge amount of data, and we would like to show it on our list that our user can scroll to all of them. In that case, if we create that amount of cells, it would use so much memory and there would be a possible crash. The solution is reusing already created cells.

First, the cells which will be visible in the first place on the screen are created. Then, user scrolls down and the initially created cells are not visible on the screen, but at the bottom of the screen we need new cells. At that point, it uses the cells that are already created and not visible by user (because they were at the top and the user passed it) In that action, the cells are dequeued from the top and reused at the bottom.

⚠️ Bear in mind that, if none of the cells can be reused, dequeueReusableCell creates new cells.

Let’s go back to our coding and run the project, it shows all the colors in our array.

initial view of the screen

Now, I prefer to have a larger cells, so I am updating the size on the canvas. I select Collection View and under the Size inspector, the Estimate Size is set to “Automatic” by default, let’s change it to “None”. Then, I update the cell size as 180x180. Now our screen is updated as following.

view of the screen with updated size

UICollectionViewFlowLayout

UICollectionViewFlowLayout is a class in the UIKit framework that provides a layout for displaying items in a grid-like pattern using a UICollectionView. It arranges items in a series of rows and columns and can be customized to specify the size, spacing, and other aspects of the layout.

8- Let’s update our collection view spacing and size with using UICollectionViewFlowLayoutDelegate. Create an extension implementing UICollectionViewDelegateFlowLayout and set the size for each item. Below code section, helps you to set each cell’s size as 100 x 100. Remember to add “collectionView.delegate = self” inside the viewDidLoad function.

view of the screen with 100x100 of each item

Here, we set hardcoded values for width and height of each cell. The column and row count may differentiate according to each device because of their screen sizes. If we would like to have specific number of columns or rows for every device, again we may use UICollectionViewFlowLayout to achieve that layout and calculate each cell’s sizes. Let’s cover that case as well in Step 9.

9- Let’s say, we would like to have 4 columns for each device.

In this case, we need to calculate each cell’s width to have 4 columns in the width of the collection view.

view of the screen with 4 columns

⚠️ Consider that, collectionView(_:layout:sizeForItemAt:) function helps you to update size of the specified item’s cell.

In the above code snippet, I added check for indexPath. If the cell’s indexPath is multiples of 5 or 8, the cell’s height is longer. Therefore, you may have different styled cells in a Collection View.

view of the screen with different sized cells

10- How about adding a section header? Before that, we need to cover what are supplementary views.

Supplementary Views (Section Headers and Footers)

Supplementary views helps you to add section header or section footer. You may easily supplementary views under the Attributes Inspector.

11- Let’s check the Section Header box and then add reuse identifier to Collection Reusable View — just like we did for cell. Similarly, section headers and footers are reused as well.

I gave “header” as reuse identifier, added Label inside the Collection Reusable View, gave text as “Color List” as shown in the below screenshot.

Let’s go back to our ViewController and add following function to our extension to see the Color List header successfully.

In the above code snippet, we dequeue reusable supplementary view, like we did for cells. Make sure you give the same reuse identifier that you set on storyboard for Collection Reusable View.

Let’s run this application. 🏃

view of the screen with section header

YES! It’s done for now. In this tutorial, we covered;

  • the comparison of UITableView and UICollectionView
  • how to implement a UICollectionView
  • UICollectionViewFlowLayout
  • Supplementary Views

Conclusion

During the process of learning UICollectionView, I got help from Mark Moeykens’ lesson in PluralSight. I totally recommend this resource, to learn this concept in more detail. UICollectionView is a long topic but to keep it short, I covered the basics. I hope you enjoyed this article. If you have any feedback on this article, you may reach me via hi@iremkaraoglu.com. If you’d like to check the source code, you may access it from here. Until next time, take care!

--

--

Irem Karaoglu
Irem Karaoglu

Written by Irem Karaoglu

iOS Developer at Hepsiburada. Interested in technology, computer science, yoga and Italian culture. to read more: iremkaraoglu.com

Responses (2)