Collection view lists

Custom cells

Sergio Ordine
3 min readAug 27, 2021

In the previous articles (here and here) we create a collection view using the compositional layout with a list template, that create a table view like collection. We also create a supplementary view as section header.

In this article, we will improve this list to use custom cells, using xib files, for both header and regular cells. The code is contained in the custom_cells branch of the article repository.

Customize header

The starting point will be customizing the header we created in the previous article.

We created a xib file and a code file for a HeaderCell class, using a UICollectionReusableView with the following layout:

Fig. 1 — Header cell custom layout

The view class identifier is set to the HeaderCell class (not the file owner). This class will have just the outlet to the title label by now.

With the header cell class created and associated with its xib layout, we can use this xib to do the header registration:

It is very close to the previous header registration. The changes are: associating the HeaderCell with the SupplementaryRegistration and using the supplementaryNib parameter to link this registration to the proper cell class and layout.

We can also notice that we are not using a cell configuration to update the information, but changing the view elements directly. The cell configuration is a way to avoid this decoupling the data population what allow us to not expose the cell internal components. We are changing it in a next article.

There is no need to change the data source to make it work due to the separation of concerns on this architecture.

Customize regular cells

The regular cell process is quite similar to the header cell. First, we create the xib and code file for a BreedRow collection view cell(UICollectionViewCell):

Fig. 2 — Breed "row" custom layout

The cell class holds just the outlets for the image and title lable:

After creating the cell we can use it to create the cell registration:

It is also very close to the cell registration we did before. We just associate the CellRegistration with the BreedRow class as well as used the cellNib parameter to link the layout and class to it.

The data source configuration also remains unchanged.

Using this new cell layouts and changes we have the following interface:

Fig. 3 — Updated list layout

It is important to emphasise that this approach is changing the cell internal structure directly, as we are working with its internal subviews. The modern cell configurations was created to hold this responsability and avoid this access. In the next article we will use cell configurations to improve this example.

Unlisted

--

--

Sergio Ordine

Software developer and educator. If you want to support me and my content production, please buy me a beer at https://www.buymeacoffee.com/sergioordine