I'm following a Advanced User Interfaces with Collection Views WWDC Session, where Apple engineers shown an approach to compose multiple UICollectionViewDataSource
objects together to achieve better code reusability and separation of concerns.
In my app I use an UICollectionView
and would like to implement a similar approach to building a UI.
An UICollectionView
requires registering classes for reuse before actually using them.
Are there any potential pitfalls if I register all the possible UICollectionViewCell
subclasses used in the app, when only a handful is actually needed for the particular screen?
By designing the app this way I'll avoid the need to introduce a custom protocol and querying the DataSource
for what cell subclasses are actually used in the UICollectionView
.
Another approach, is to register the cell every time before dequeuing it:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model =... GET MODEL
let cellClass = MODEL.cellClass
// Registering the cell class every time before dequeuing, ensuring it will be registered before dequeued
collectionView.registerCellClass(cellClass)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellClass.reuseIdentifier(),
for: indexPath)
cell.configure(model)
return cell
}
What are the drawbacks of this approach, if any?
Registering before dequeueing is likely very inefficient, so I would not recommend that out of the options you have.
Although I don't have true diagnostics to show it, registering every possible cell class in viewDidLoad
should not greatly impact performance, since this is what Apple recommends.
You can make separate methods to register particular cell classes depending on the class of the data source. However, in the grand scheme of things, this is not something that you should want to focus on if you want to improve performance or speed.