Created
February 28, 2023 12:49
-
-
Save srstanic/fb3c0ce8cc3132de48ed433ca12e8ec9 to your computer and use it in GitHub Desktop.
MyCollectionViewController #2
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 | |
struct CollectionItemModel { | |
let title: String? | |
let image: UIImage? | |
} | |
struct CellController { | |
var model: CollectionItemModel | |
func getCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { | |
if let image = model.image { | |
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "image", for: indexPath) | |
cell.largeContentImage = image | |
return cell | |
} else if let title = model.title { | |
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "text", for: indexPath) | |
cell.largeContentTitle = title | |
return cell | |
} | |
return UICollectionViewCell() | |
} | |
} | |
/// 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(model: .init(title: nil, image: UIImage(named: "what"))), | |
CellController(model: .init(title: "Text", image: nil)) | |
] | |
collectionViewController.cellControllers = cellControllers | |
return collectionViewController | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment