Created
June 1, 2019 09:59
-
-
Save OscarApeland/80d1b1dd9f7534ffa0dc8c7173989ef6 to your computer and use it in GitHub Desktop.
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 | |
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