Skip to content

Instantly share code, notes, and snippets.

@srstanic
Created February 28, 2023 12:53
Show Gist options
  • Save srstanic/fd381a2cd82f41861b779a73a6060ed8 to your computer and use it in GitHub Desktop.
Save srstanic/fd381a2cd82f41861b779a73a6060ed8 to your computer and use it in GitHub Desktop.
MyCollectionViewController #3
import UIKit
protocol CellController {
func getCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell
}
struct TextItemModel {
let title: String
}
struct ImageItemModel {
let image: UIImage
}
struct TextCellController: CellController {
var model: TextItemModel
func getCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "text", for: indexPath)
cell.largeContentTitle = model.title
return cell
}
}
struct ImageCellController: CellController {
var model: ImageItemModel
func getCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "text", for: indexPath)
cell.largeContentImage = model.image
return cell
}
}
/// First set `model` and then present on screen.
final class MyCollectionViewController: UICollectionViewController {
var cellControllers: [CellController]?
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellController = cellControllers?[indexPath.row]
let cell = cellController?.getCell(collectionView: collectionView, indexPath: indexPath) ?? UICollectionViewCell()
return cell
}
}
func createMyCollectionViewController() -> MyCollectionViewController {
let collectionViewController = MyCollectionViewController()
let cellControllers: [CellController] = [
ImageCellController(model: .init(image: UIImage(named: "what")!)),
TextCellController(model: .init(title: "Text"))
]
collectionViewController.cellControllers = cellControllers
return collectionViewController
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment