Skip to content

Instantly share code, notes, and snippets.

@rtimpone
Last active April 10, 2018 14:52
Show Gist options
  • Save rtimpone/9e32bf954e8d8e3c91c5548c0e25f2da to your computer and use it in GitHub Desktop.
Save rtimpone/9e32bf954e8d8e3c91c5548c0e25f2da to your computer and use it in GitHub Desktop.
An extension that allows UITableViews to automatically register nib-based UITableViewCells when it attempts to dequeue them. Makes working with nib-based table view cells much easier.
protocol NibBased {
static var nibName: String { get }
}
extension NibBased {
static var nibName: String {
return String(describing: self)
}
}
extension UITableView {
private struct AssociatedKeys {
static var registeredNibBasedCells = "kRegisteredNibBasedCells"
}
//this allows us to add a stored property of type Set<String> to all UITableViews via an extension
var registeredNibBasedCells: Set<String>? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.registeredNibBasedCells) as? Set<String>
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.registeredNibBasedCells, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
func dequeueReusableCell<T: UITableViewCell>(ofType type: T.Type) -> T where T: NibBased {
if registeredNibBasedCells == nil {
registeredNibBasedCells = Set<String>()
}
guard let registeredCells = registeredNibBasedCells else {
fatalError("Unable to access the set of registered nib-based cells")
}
let className = type.nibName
if !registeredCells.contains(className) {
let nib = UINib(nibName: className, bundle: nil)
register(nib, forCellReuseIdentifier: className)
registeredNibBasedCells?.insert(className)
}
guard let dequeuedCell = dequeueReusableCell(withIdentifier: className) else {
fatalError("Unable to dequeue reusable cell with identifier '\(className)'")
}
guard let castedCell = dequeuedCell as? T else {
fatalError("Unable to cast dequeued cell to type '\(className)'")
}
return castedCell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment