Skip to content

Instantly share code, notes, and snippets.

@meyusufdemirci
Created September 18, 2021 13:16
Show Gist options
  • Select an option

  • Save meyusufdemirci/f5562591139c8e3f327eaad5d9f040dd to your computer and use it in GitHub Desktop.

Select an option

Save meyusufdemirci/f5562591139c8e3f327eaad5d9f040dd to your computer and use it in GitHub Desktop.
Register and use collection view cells with generic type
// 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