Make your UITableView & UICollectionView lighter with MVVM

Sometimes, working with both UITableView and UICollectionView ending up with bloated views or even controllers. Things more complicated when we need to change our datatype dynamically. Lets say we have two section like below;

Let say we have two section one shows current orders and second one shows completed orders.

Below screen there are two separated section that means we need two seperate model and this two models configured accordinly. If I select “Orders” I have to prepare my cell in table view with Order model. In contrast when I select “Completed Orders” I have to prepare my cell in tableview with related model as well.

I have created two different model for this situation first one is for active order and second one is for completed orders like so; For this kind of situtations it would more benifical to seperate data sources. We should not re-use our data source files into same application. Instead we should create our data source per table&collection views. By doing so, we can test our view models, models and even our data sources!

For to keep our models are immutable I use struct instead of class.

And my ViewModels has very simple job right now.

Our data sources only implementing UITableViewDataSource or UICollectionViewDataSource

And finally, our view controller does only one thing; mediating between views and view models! Generally we should keep our view controller light. This way if we can make unit test our view models that increase our test coverage and our app robutness and doing a little SRP(Single Responsibility Principle) rule.

As you can see above my view controller doing only view related jobs. Like binding my data source class into table view.


When make thins red-green-refactor criteria in this approach we can test almost every business logic. We can test our model, view model and even data source like I said before;