Skip to content

Instantly share code, notes, and snippets.

@ex3ndr
Created September 27, 2015 20:59
Show Gist options
  • Save ex3ndr/7d23be0f3d709d2cc488 to your computer and use it in GitHub Desktop.
Save ex3ndr/7d23be0f3d709d2cc488 to your computer and use it in GitHub Desktop.
Extension to UITableView that allows to avoid explict cell classes registrations
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
// Cell automatic registration and dequeuing
private var registeredCells = "cells!"
extension UITableView {
private func cellTypeForClass<T where T: UITableViewCell>(cellClass: T.Type) -> String {
let cellReuseId = "\(T.self)"
var registered: ([String])! = getAssociatedObject(tableView, associativeKey: &registeredCells)
var found = false
if registered != nil {
if registered.contains(cellReuseId) {
found = true
} else {
registered.append(cellReuseId)
setAssociatedObject(self, value: registered, associativeKey: &registeredCells)
}
} else {
setAssociatedObject(self, value: [cellReuseId], associativeKey: &registeredCells)
}
if !found {
self.registerClass(T.self, forCellReuseIdentifier: cellReuseId)
}
return cellReuseId
}
func dequeueCell<T where T: UITableViewCell>(indexPath: NSIndexPath? = nil) -> T {
let reuseId = cellTypeForClass(T.self)
if indexPath != nil {
return self.dequeueReusableCellWithIdentifier(reuseId, forIndexPath: indexPath!) as! T
} else {
return self.dequeueReusableCellWithIdentifier(reuseId) as! T
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment