An MVVM approach to UICollectionView — Part 2

Enhance reusability of ViewModels and Cells

This is Part 2 of a series of articles about how I usually organize components related to UICollectionViews and UITableViews. If you haven’t read the first part, you can find it here: Part 1 — Make your content independent

In Part 1 we have encapsulated the cell binding logic inside ItemViewModel:

The StandardCellViewModel of Part 1

Probably, if you already know something about MVVM there are a couple of objections about the above implementation:

  • Your are not using Interfaces
  • Your ViewModel should not know your View (why aren’t you using interfaces?)
  • Your ViewModel can not be used with different Views
  • Your View can not be used with different ViewModels
  • What about Cell dimensions?

Keeping the last question to the next part, let’s start with something very important like splitting the ViewModel from the View with an interface. Usually to do this I prefer to define the Protocol to describe the data that the ViewModel could pass to the View. This is because the ViewModel should not know how the view is organized.

A ViewModel with the view described by an interface

Even if you present cells that contains data received from async resources this approach helps you to bind those kind of behaviors. You can encapsulate all the logic to get the async contents in the ViewModel, maintaining the cell as simple as possible:

A ViewModel with async content

Now that we are finally using an Interface to represent the View on the ViewModel side, ViewModel could be used with different cells. Let’s go and see how I usually declare it:

A UICollectionViewCell with the ResourceCell compliancy

As you can see here, the compliancy to the ViewModel-View Interface is made in an extension. I usually do this to keep only the layout stuff in the cell class declaration. This gives to me the capability to write multiple extensions, one for each ViewModel-View Interface, giving to every component it’s specific responsability. You can even split the extensions declaration to different files to maintain a well organized project.

How I organize my UICollectionViewCells

This approach enhances a lot of code reusability. At this point you could use the same layout in different parts of your app to present different contents, or the same ViewModel could be used in different collections to present your content in different ways.

If you find this hints handy, please tell me and I’ll be pretty happy to discuss with you or write about other parts of this implementation like the user interaction or the sizing and layouting of the cells.