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:
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.
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:
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:
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.
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.