Skip to content

Instantly share code, notes, and snippets.

@cyrilchandelier
Created September 2, 2019 01:32
Show Gist options
  • Save cyrilchandelier/d074f89aa0975a78aa7d883f832dd631 to your computer and use it in GitHub Desktop.
Save cyrilchandelier/d074f89aa0975a78aa7d883f832dd631 to your computer and use it in GitHub Desktop.
UICollectionView extension to easily register/dequeue cells
import UIKit
protocol UICollectionViewRegisterable {
static var cellIdentifier: String { get }
static var cellNib: UINib { get }
}
extension UICollectionView {
func register(type: UICollectionViewRegisterable.Type) {
register(type.cellNib, forCellWithReuseIdentifier: type.cellIdentifier)
}
func dequeueCell<CellType: UICollectionViewRegisterable>(at indexPath: IndexPath) -> CellType {
guard let cell = dequeueReusableCell(withReuseIdentifier: CellType.cellIdentifier, for: indexPath) as? CellType else {
fatalError("UICollectionView should dequeue a cell of type \(CellType.self)")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment