Created
September 18, 2021 13:16
-
-
Save meyusufdemirci/f5562591139c8e3f327eaad5d9f040dd to your computer and use it in GitHub Desktop.
Register and use collection view cells with generic type
This file contains hidden or 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
| // USAGE | |
| collectionView.register([CELL_CLASS_NAME.self]) | |
| func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | |
| let cell: CELL_CLASS_NAME = collectionView.dequeueReusableCell(indexPath: indexPath) | |
| } | |
| // USAGE | |
| import UIKit | |
| extension UICollectionView { | |
| func register(_ cells: [UICollectionViewCell.Type]) { | |
| cells.forEach { cell in | |
| register(cell.self, forCellWithReuseIdentifier: cell.identifier) | |
| } | |
| } | |
| func dequeueReusableCell<T: UICollectionViewCell>(indexPath: IndexPath) -> T { | |
| dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as! T | |
| } | |
| } | |
| extension UICollectionViewCell { | |
| static var identifier: String { | |
| String(describing: self.self) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment