Skip to content

Instantly share code, notes, and snippets.

@matthiasnys
Last active May 27, 2017 13:46
Show Gist options
  • Save matthiasnys/96ae8eec52d3b63ed8c307b43defb116 to your computer and use it in GitHub Desktop.
Save matthiasnys/96ae8eec52d3b63ed8c307b43defb116 to your computer and use it in GitHub Desktop.
Easy to use Cell reuse in TableView and CollectionView. Add this file to your Swift project to get going!
//
// Reusable.swift
// B-NYS GCV
//
// Created by Matthias Nys on 12/01/2017.
// Copyright © 2017 B-NYS. All rights reserved.
// https://gist.github.com/matthiasnys/96ae8eec52d3b63ed8c307b43defb116
//
import UIKit
protocol ReusableView: class {
static var defaultReuseIdentifier: String { get }
}
extension ReusableView where Self: UIView {
static var defaultReuseIdentifier: String {
return NSStringFromClass(self)
}
}
extension UICollectionViewCell: ReusableView { }
extension UICollectionView {
func register<T: UICollectionViewCell>(class: T.Type) where T: ReusableView {
register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
}
func dequeueReusableCell<T: UICollectionViewCell >(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
}
return cell
}
}
extension UITableViewCell: ReusableView { }
extension UITableView {
func test() {
self.register(class: UITableViewCell.self)
}
func register<T: UITableViewCell>(class: T.Type) where T: ReusableView {
register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell >(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment