Get started with UICollectionView đ
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.
3- Now, set the collection view constraints to make it cover the whole screen.
Set 0 as constraints for all directions.
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.
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.
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.
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.
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.
â ď¸ 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.
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. đ
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!