Created
September 27, 2015 20:59
-
-
Save ex3ndr/7d23be0f3d709d2cc488 to your computer and use it in GitHub Desktop.
Extension to UITableView that allows to avoid explict cell classes registrations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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: ®isteredCells) | |
var found = false | |
if registered != nil { | |
if registered.contains(cellReuseId) { | |
found = true | |
} else { | |
registered.append(cellReuseId) | |
setAssociatedObject(self, value: registered, associativeKey: ®isteredCells) | |
} | |
} else { | |
setAssociatedObject(self, value: [cellReuseId], associativeKey: ®isteredCells) | |
} | |
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