Skip to content

Instantly share code, notes, and snippets.

@GemmaDelOlmo
Created December 1, 2017 10:44
Show Gist options
  • Select an option

  • Save GemmaDelOlmo/7aafec987d3b3a196a314ba15dbe5287 to your computer and use it in GitHub Desktop.

Select an option

Save GemmaDelOlmo/7aafec987d3b3a196a314ba15dbe5287 to your computer and use it in GitHub Desktop.
UITableViewExtension to help reuse cells
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