Skip to content

Instantly share code, notes, and snippets.

@OscarApeland
Created June 1, 2019 09:59
Show Gist options
  • Save OscarApeland/80d1b1dd9f7534ffa0dc8c7173989ef6 to your computer and use it in GitHub Desktop.
Save OscarApeland/80d1b1dd9f7534ffa0dc8c7173989ef6 to your computer and use it in GitHub Desktop.
import UIKit
extension UICollectionView {
func register<CellClass: UICollectionReusableView>(_ cellClass: CellClass.Type, ofKind kind: String? = nil) {
let cellId = String(describing: type(of: cellClass.classForCoder()))
if let kind = kind {
register(cellClass, forSupplementaryViewOfKind: kind, withReuseIdentifier: cellId)
} else if let collectionViewCellClass = cellClass as? UICollectionViewCell.Type {
register(collectionViewCellClass, forCellWithReuseIdentifier: cellId)
}
}
func dequeue<CellClass: UICollectionReusableView>(_ cellClass: CellClass.Type, ofKind kind: String? = nil, for indexPath: IndexPath) -> CellClass {
let cellId = String(describing: type(of: cellClass.classForCoder()))
if let kind = kind {
return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: cellId, for: indexPath) as! CellClass
} else {
return dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CellClass
}
}
}
// Usage
collectionView.register(CustomCell.self)
let typedCell = collectionView.dequeue(CustomCell.self, for: indexPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment