DEV Community

Cover image for UITableView with multiple kinds of cells (also works on UICollectionView)
Fabrício Masiero
Fabrício Masiero

Posted on

UITableView with multiple kinds of cells (also works on UICollectionView)

Hi everyone =D



I will show in this article how to use multiple types of cells in your UITableView or UICollectionView.
A lot of developers do that in the wrong way, using sections or rows to present another kind of cell.

This tutorial will be separated on 3 fronts:

  • 1 - Create a model
  • 2 - Register cells on your controller
  • 3 - Organize it on cellForRow

Creating a model

First of all, I create a simple model to populate my table.

The secret of this model is the enum VehicleType. That changes everything!

Creating and register cell on table

After that, I create 3 kinds of cell:

Bike Cell

Bike Cell
Car Cell
Car Cell

And finally, Motorbike Cell
Moto Cell

And create an array of vehicles:

Set cell on cellForRow

Ok, we are almost done! What we need to do right now is configure our cellForRow atIndexPath or itemForRow atIndexPath.
Write an switch case to determine what kind of cell table will present. Like this example:

But, if you saw, each cell has a different size. Ok, let's do the same thing on heightForRow atIndexPath

And that's it! Simple, beautiful, and very easy!

I don't prepared a beautiful layout on these cells, but, take a look, we have 3 different cells on the same Table or Collection:

View Controller

Download source code here =D

I hope I have helped everyone looking for this change.
If you would like to extend the discussion, call me on Twitter

Happy Coding :)

Top comments (1)

Collapse
 
steven_thompson_144188290 profile image
Steven Thompson

But all those switch statements are now unnecessay. Each model can now handle this.