Skip to content

Instantly share code, notes, and snippets.

@zef
Created March 14, 2019 21:17
Show Gist options
  • Save zef/1597e5c125553081d299ba64fc4af1d1 to your computer and use it in GitHub Desktop.
Save zef/1597e5c125553081d299ba64fc4af1d1 to your computer and use it in GitHub Desktop.
Reusable cells for iOS
//
// Reusable.swift
//
// Created by Zef Houssney
//
import UIKit
protocol Reusable {
static var reuseIdentifier: String { get }
}
extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UITableViewCell: Reusable { }
extension UICollectionReusableView: Reusable { }
extension UITableViewHeaderFooterView: Reusable { }
extension UICollectionView {
func register(cellType type: UICollectionViewCell.Type) {
register(type, forCellWithReuseIdentifier: type.reuseIdentifier)
}
func registerNib(cellType type: UICollectionViewCell.Type) {
register(UINib(nibName: type.reuseIdentifier, bundle: nil), forCellWithReuseIdentifier: type.reuseIdentifier)
}
func dequeueCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("You need to register cell of type `\(T.reuseIdentifier)`")
}
return cell
}
func registerSupplementaryView(suplementaryViewType type: UICollectionReusableView.Type, kind: String) {
register(type, forSupplementaryViewOfKind: kind, withReuseIdentifier: type.reuseIdentifier)
}
func dequeueSupplementaryView<T: UICollectionReusableView>(ofKind elementKind: String, for indexPath: IndexPath) -> T {
guard let supplementaryView = dequeueReusableSupplementaryView(
ofKind: elementKind,
withReuseIdentifier: T.reuseIdentifier,
for: indexPath) as? T else {
fatalError("You need to register supplementaryView of type `\(T.reuseIdentifier)` for kind `\(elementKind)`")
}
return supplementaryView
}
}
extension UITableView {
func register(cellType type: UITableViewCell.Type) {
register(type, forCellReuseIdentifier: type.reuseIdentifier)
}
func registerNib(cellType type: UITableViewCell.Type) {
register(UINib(nibName: type.reuseIdentifier, bundle: nil), forCellReuseIdentifier: type.reuseIdentifier)
}
func dequeueCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("You need to register cell of type `\(T.reuseIdentifier)`")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment