Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active July 6, 2018 17:29
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jasdev/efe1feb9179fa1f8dd04 to your computer and use it in GitHub Desktop.
Save jasdev/efe1feb9179fa1f8dd04 to your computer and use it in GitHub Desktop.
An approach to safer UITableViewCell and UICollectionViewCell reuse
class CustomCell: UITableViewCell, Reusable {
class var reuseIdentifier: String {
return "customCell"
}
}
class SupaHotCustomCell: CustomCell {
override class var reuseIdentifier: String {
return "supaHotCustomCell"
}
}
import UIKit
class CustomCell: UITableViewCell, Reusable {
static let reuseIdentifier = "customCell"
}
class SomeTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerReusable(CustomCell.self)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusable(CustomCell.self)
}
}
extension UICollectionView {
func registerReusable<T: Reusable>(cellClass: T.Type) {
registerClass(cellClass, forCellWithReuseIdentifier: cellClass.reuseIdentifier)
}
func dequeueReusable<T: Reusable>(cellClass: T.Type, forIndexPath: NSIndexPath) -> T {
guard let cell = dequeueReusableCellWithReuseIdentifier(cellClass.reuseIdentifier, forIndexPath: forIndexPath) as? T else {
fatalError("Misconfigured cell type, \(cellClass)!")
}
return cell
}
}
import UIKit
// Shared protocol to represent reusable items, e.g. table or collection view cells
protocol Reusable: class {
static var reuseIdentifier: String { get }
}
extension UITableView {
// Allowing UITableView class registration with Reusable
func registerReusable<T: Reusable>(cellClass: T.Type) {
registerClass(cellClass, forCellReuseIdentifier: cellClass.reuseIdentifier)
}
// Safely dequeue a `Reusable` item
func dequeueReusable<T: Reusable>(cellClass: T.Type) -> T {
guard let cell = dequeueReusableCellWithIdentifier(cellClass.reuseIdentifier) as? T else {
fatalError("Misconfigured cell type, \(cellClass)!")
}
return cell
}
// Safely dequeue a `Reusable` item for a given index path
func dequeueReusable<T: Reusable>(cellClass: T.Type, forIndexPath indexPath: NSIndexPath) -> T {
guard let cell = dequeueReusableCellWithIdentifier(cellClass.reuseIdentifier, forIndexPath: indexPath) as? T else {
fatalError("Misconfigured cell type, \(cellClass)!")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment