Created
December 1, 2017 10:44
-
-
Save GemmaDelOlmo/7aafec987d3b3a196a314ba15dbe5287 to your computer and use it in GitHub Desktop.
UITableViewExtension to help reuse cells
This file contains hidden or 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
| extension UITableView { | |
| func register<T: UITableViewCell>(_: T.Type) where T: NibLoadableView { | |
| let bundle = Bundle(for: T.self) | |
| let nib = UINib(nibName: T.nibName, bundle: bundle) | |
| self.register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) | |
| } | |
| func registerHeader<T: UIView>(_: T.Type) where T: ReusableView, T: NibLoadableView { | |
| let bundle = Bundle(for: T.self) | |
| let nib = UINib(nibName: T.nibName, bundle: bundle) | |
| self.register(nib, forHeaderFooterViewReuseIdentifier: T.defaultReuseIdentifier) | |
| } | |
| func dequeueReusableCell<T: UITableViewCell>(_:T.Type, forIndexPath indexPath: IndexPath) -> T { | |
| guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else { | |
| fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") | |
| } | |
| return cell | |
| } | |
| func dequeueReusableCell<T: UITableViewCell>(_:T.Type) -> T { | |
| guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier) as? T else { | |
| fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") | |
| } | |
| return cell | |
| } | |
| func dequeueReusableHeaderFooter<T: UIView>(_:T.Type) -> T where T: ReusableView { | |
| guard let headerFooter = dequeueReusableHeaderFooterView(withIdentifier: T.defaultReuseIdentifier) as? T else { | |
| fatalError("Could not dequeue header/footer with identifier: \(T.defaultReuseIdentifier)") | |
| } | |
| return headerFooter | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment