Created
July 28, 2019 07:12
-
-
Save ppth0608/eba4781fa91c45688f3a8f4f431e9cf2 to your computer and use it in GitHub Desktop.
How to make `register`, `dequeueReusableCell` functions more flexibly
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 | |
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