How to have more than one type of cell in a Collection View
Collection views in iOS are awesome. You can use them to build complex custom layouts and since iOS 13 you can use Compositional Layouts to quickly build good looking layouts that would take forever to accomplish on iOS 12 and below.
But what if you want to use more than one type of cell in your layout?
If you're building your app without storyboard you register collection view cells using the register
method on UICollectionView
. If you want to use more than one cell type, all you need to do is call register
multiple times:
collectionView.register(CellTypeOne.self, forCellWithReuseIdentifier: "CellTypeOne")
collectionView.register(CellTypeTwo.self, forCellWithReuseIdentifier: "CellTypeTwo")
Each cell type has its own class and its own reuse identifier. In the collection view's cellForItemAt
delegate method you can return either of your registered cells like this:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let dequeuedCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellTypeOne", for: indexPath)
guard let cellOne = dequeuedCell as? CellTypeOne else {
fatalError("Wrong cell type for section 0. Expected CellTypeOne")
}
// configure your CellTypeOne
return cellOne
} else {
let dequeuedCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellTypeTwo", for: indexPath)
guard let cellTwo = dequeuedCell as? CellTypeTwo else {
fatalError("Wrong cell type for section 0. Expected CellTypeTwo")
}
// configure your CellTypeTwo
return cellTwo
}
}
In my example, I want to use CellTypeOne
for the first section in my collection view and CellTypeTwo
for all other sections. You can use any logic you want to determine which cell should be used. Notice that using multiple cell types ultimately isn't too different from using one cell type. The only difference is that you'll have an if
somewhere to determine which cell type you want to dequeue.
If you're using Storyboards to build your app the process of dequeuing cells is the same as it is when you're doing everything in code. The only difference is how you register the cells on your collection view. It's perfectly fine to mix Storyboards and programmatic so you could use register
to register new cells on the collection view that you created in a Storyboard.
Alternatively, you can drag more than one cell from the Object Library into your collection view, assign a subclass and reuse identifier for the cell and design it as needed. Just like you would for a single cell. Dragging multiple cells into your collection view in a Storyboard automatically registers these cells on your collection view. You can use and dequeue them just like I showed you in the code above.
If you have any questions about this tip, or if you have feedback for me, don't hesitate to reach out on Twitter.