An MVVM approach to UICollectionView — Part 1

Make your content independent.

Andrea Altea
2 min readOct 21, 2018

--

Update: Now this is available in my first framework, PowerTools

What’s my problem with CollectionViews

Maybe not for everyone, but UICollectionView and UITableView could be complex, at least more than standard Views, and that’s because they are dynamic. Content is not requested all together and the order itself depends on the user interaction with those components.

If this isn’t enough, the structure of the dataSource pushes people to keep all the logic to populate cells inside the collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath)
method,

here an example:

Trust me, this could only become worse.

Let’s try to put your shit together

As I said before, the main problem of UICollectionViews is that they are dynamic, but to have a simple representation of the content, we need to make it static.

To do this, I usually prefer to incapsulate my business resources in a new entity representing the items inside the UICollectionView. In particular, I would create an array of items that represents the sections of my collection, and every section will contain the related items.

Typically I represent this content like this:

Now, we need something that could bridge the content from our “ViewModel” representation to a real collection view, so a UICollectionViewDataSource that uses an array of SectionViewModels to represent the content of the collection:

With this kind of representation, everything in the UICollectionViewDataSource is generic, and we only need to define the real view models that bind content into the CollectionViewCell:

This is just a synthesis, but it’s the bare bone of how I handle the dataSources of UICollectionViews in all my apps now.

I use this pattern profusely to enhance code reusability and responsibility encapsulation in my models, so, if you find this hints handy, please tell me and i’ll be pretty happy to discuss about this or write about other parts of the implementation, like the user interaction or the sizing and layouting of the cells.

Part 2 is available here :)

--

--

Andrea Altea

I’m an iOS Developer at Shopfully Group in Italy, I love coding and do stuff just because it’s fun!