Skip to content

Instantly share code, notes, and snippets.

@krodak
Last active January 19, 2016 08:26
Show Gist options
  • Save krodak/058944edf0991467aa3a to your computer and use it in GitHub Desktop.
Save krodak/058944edf0991467aa3a to your computer and use it in GitHub Desktop.
Safely dequeue any `UITableViewCell`'s subclass instance with assumption that .xib name is the same as subclass name.
extension UITableView {
public func dequeueReusableCell<T:UITableViewCell>(type: T.Type) -> T {
let tableCell : T
let cellIdentifier = String(T)
if let cell = self.dequeueReusableCellWithIdentifier(cellIdentifier) as? T {
tableCell = cell
} else if let _ = NSBundle(forClass: T.classForCoder()).pathForResource(cellIdentifier, ofType:"nib") {
self.registerNib(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier)
if let cell = NSBundle(forClass: T.classForCoder()).loadNibNamed(cellIdentifier, owner: nil, options: nil)[0] as? T {
tableCell = cell
} else {
//if anyone had better suggestion for fallback, you're welcome to comment
tableCell = T(style: .Default, reuseIdentifier: cellIdentifier)
}
} else {
tableCell = T(style: .Default, reuseIdentifier: cellIdentifier)
}
return tableCell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment