Skip to content

Instantly share code, notes, and snippets.

@sger
Last active May 6, 2020 07:53
Show Gist options
  • Save sger/f5ffdd4cece6c7b5ca24e23f0459ce08 to your computer and use it in GitHub Desktop.
Save sger/f5ffdd4cece6c7b5ca24e23f0459ce08 to your computer and use it in GitHub Desktop.
import UIKit
final class ReusableCollectionViewDataSource<T, V>: NSObject,
UICollectionViewDataSource where V: ReusableCollectionViewCell<T> {
typealias ConfigureCell = (T, V) -> Void
var models: [T]
private let configureCell: ConfigureCell
init(models: [T], cellConfigurator: @escaping ConfigureCell) {
self.models = models
self.configureCell = cellConfigurator
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return models.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: V = collectionView.dequeue(for: indexPath)
let model = models[indexPath.row]
configureCell(model, cell)
return cell
}
}
class ReusableCollectionViewCell<V>: UICollectionViewCell {
var model: V?
}
/* private var dataSource: ReusableCollectionViewDataSource<Model, Cell>?
self?.dataSource = ReusableCollectionViewDataSource(models: data) { model, cell in
cell.model = model
}
self?.collectionView.dataSource = self?.dataSource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment