Last active
September 29, 2022 07:56
-
-
Save yucelokan/bda9f1ce464f9d8a104d96f11b5997af to your computer and use it in GitHub Desktop.
To register and dequeue cells.
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
public extension UIView { | |
class var identifier: String { | |
String(describing: self) | |
} | |
} | |
public extension UITableView { | |
func registerNib(_ type: UITableViewCell.Type, bundle: Bundle) { | |
register( | |
UINib(nibName: type.identifier, bundle: bundle), | |
forCellReuseIdentifier: type.identifier | |
) | |
} | |
func dequeueCell<CellType: UITableViewCell>(type: CellType.Type, indexPath: IndexPath) -> CellType { | |
guard let cell = dequeueReusableCell(withIdentifier: CellType.identifier, for: indexPath) as? CellType else { | |
fatalError("Wrong type of cell \(type)") | |
} | |
return cell | |
} | |
func dequeueHeaderFooter<Header: UITableViewHeaderFooterView>(type: Header.Type) -> Header { | |
guard let view = dequeueReusableHeaderFooterView(withIdentifier: Header.identifier) as? Header else { | |
fatalError("Wrong type of header/footer view \(type)") | |
} | |
return view | |
} | |
} | |
public extension UICollectionView { | |
func registerNib(_ type: UICollectionViewCell.Type, bundle: Bundle) { | |
register( | |
UINib(nibName: type.identifier, bundle: bundle), | |
forCellWithReuseIdentifier: type.identifier | |
) | |
} | |
func registerHeader(_ type: UICollectionReusableView.Type, bundle: Bundle) { | |
register( | |
UINib(nibName: type.identifier, bundle: bundle), | |
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: type.identifier | |
) | |
} | |
func dequeueCell<CellType: UICollectionViewCell>(type: CellType.Type, indexPath: IndexPath) -> CellType { | |
guard let cell = dequeueReusableCell( | |
withReuseIdentifier: CellType.identifier, for: indexPath | |
) as? CellType else { | |
fatalError("Wrong type of cell \(type)") | |
} | |
return cell | |
} | |
func dequeueHeaderView<ViewType: UICollectionReusableView>(type: ViewType.Type, indexPath: IndexPath) -> ViewType { | |
guard let headerView = dequeueReusableSupplementaryView( | |
ofKind: | |
UICollectionView.elementKindSectionHeader, | |
withReuseIdentifier: ViewType.identifier, | |
for: indexPath | |
) as? ViewType else { | |
fatalError("Wrong type of header view \(type)") | |
} | |
return headerView | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment