Skip to content

Instantly share code, notes, and snippets.

@ppth0608
Created July 28, 2019 07:12
Show Gist options
  • Save ppth0608/eba4781fa91c45688f3a8f4f431e9cf2 to your computer and use it in GitHub Desktop.
Save ppth0608/eba4781fa91c45688f3a8f4f431e9cf2 to your computer and use it in GitHub Desktop.
How to make `register`, `dequeueReusableCell` functions more flexibly
import UIKit
protocol Reusable { }
extension UITableViewCell: Reusable { }
extension UICollectionViewCell: Reusable { }
extension UITableView {
func register<T: Reusable>(_ type: T.Type) {
let identifier = String(describing: T.self)
let nib = UINib(nibName: identifier, bundle: nil)
self.register(nib, forCellReuseIdentifier: identifier)
}
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: T.self), for: indexPath) as? T else {
fatalError("❗️Couldn't dequeue cell with identifier \(String(describing: T.self))")
}
return cell
}
}
extension UICollectionView {
func register<T: Reusable>(_ type: T.Type) {
let identifier = String(describing: T.self)
let nib = UINib(nibName: identifier, bundle: nil)
self.register(nib, forCellWithReuseIdentifier: identifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else {
fatalError("❗️Couldn't dequeue cell with identifier \(String(describing: T.self))")
}
return cell
}
}
/////////
//Usage//
/////////
collectionView.register(ImageCell.self)
let cell = collectionView.dequeueReusableCell(for: indexPath) as ImageCell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment