Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Last active September 3, 2021 15:41
Show Gist options
  • Save thomsmed/15dce460b8b604e15e47e39a5b756a7f to your computer and use it in GitHub Desktop.
Save thomsmed/15dce460b8b604e15e47e39a5b756a7f to your computer and use it in GitHub Desktop.
Useful UITableView extensions
//
// UITableView+Extensions.swift
//
import Foundation
import UIKit
protocol ReusableCell: AnyObject {
static var reuseIdentifier: String { get }
}
extension ReusableCell {
static var reuseIdentifier: String { String(describing: self) }
}
extension UITableViewCell: ReusableCell {}
extension UITableViewHeaderFooterView: ReusableCell {}
extension UITableView {
func dequeue<T: ReusableCell>(as type: T.Type, identifier: String? = nil) -> T {
guard let cell = dequeueReusableCell(withIdentifier: identifier ?? type.reuseIdentifier) as? T else {
fatalError("Unable to dequeue \(T.self)")
}
return cell
}
func dequeueHeaderFooter<T: ReusableCell>(as type: T.Type, identifier: String? = nil) -> T {
guard let headerFooter = dequeueReusableHeaderFooterView(withIdentifier: identifier ?? type.reuseIdentifier) as? T else {
fatalError("Unable to dequeue \(T.self)")
}
return headerFooter
}
func registerFromNib<T: ReusableCell>(_ type: T.Type) {
register(UINib(nibName: type.reuseIdentifier, bundle: nil), forCellReuseIdentifier: type.reuseIdentifier)
}
func register<T: ReusableCell>(_ type: T.Type) {
register(T.self, forCellReuseIdentifier: type.reuseIdentifier)
}
func registerHeaderFooter<T: ReusableCell>(_ type: T.Type) {
register(T.self, forHeaderFooterViewReuseIdentifier: type.reuseIdentifier)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment