Created
February 28, 2023 12:53
-
-
Save srstanic/fd381a2cd82f41861b779a73a6060ed8 to your computer and use it in GitHub Desktop.
MyCollectionViewController #3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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