-
Notifications
You must be signed in to change notification settings - Fork 13
Open
Labels
Description
I know most of our projects typically separate out table/collection view functionality into separate objects. We should take this a step further and make some generic controllers to handle this (which I think some projects already do). Since SwiftUI is coming (eventually), we shouldn't spend too much time on it, but at least handling the basic case of presenting a list of identical cells should be a goal.
I spent a few minutes doodling so here's something to get started:
class CollectionController<ItemType, CellType: UICollectionViewCell>: NSObject, UICollectionViewDataSource {
private let items: [ItemType]
private let cellConfigurationBlock: (ItemType, CellType) -> Void
init(items: [ItemType], cellConfigurationBlock: @escaping (ItemType, CellType) -> Void) {
self.items = items
self.cellConfigurationBlock = cellConfigurationBlock
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CellType.self), for: indexPath) as? CellType else { fatalError("Unable to dequeue cell of type '\(CellType.self)'") }
let item = items[indexPath.item]
cellConfigurationBlock(item, cell)
return cell
}
}