Skip to content

Instantly share code, notes, and snippets.

@Infinity-James
Created April 20, 2018 08:37
Show Gist options
  • Save Infinity-James/d4dca026287672a97c507f02d0fa21be to your computer and use it in GitHub Desktop.
Save Infinity-James/d4dca026287672a97c507f02d0fa21be to your computer and use it in GitHub Desktop.
Allows for easy registration and dequeue of table view and collection view cells.
import UIKit
// MARK: Nib Loadable
public protocol NibLoadable {
/// The name of the .xib file in which this view is defined.
static var nibName: String { get }
}
// MARK: Nib Loadable Convenience
public extension NibLoadable where Self: UIView {
static var nibName: String { return NSStringFromClass(self).components(separatedBy: ".").last! }
}
// MARK: Reusable View
/**
Indicates that a view can be reused provided it matches a provided identifier.
*/
public protocol ReusableView: class {
/// The identifier for this type of reusable view.
static var defaultReuseIdentifier: String { get }
}
// MARK: Reusable View Convenience
public extension ReusableView where Self: UIView {
static var defaultReuseIdentifier: String { return NSStringFromClass(self).components(separatedBy: ".").last! }
}
extension UICollectionViewCell: ReusableView { }
extension UITableViewCell: ReusableView { }
// MARK: Registration
public extension UICollectionView {
func register<T: UICollectionViewCell>(_: T.Type) {
register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
}
func register<T: UICollectionViewCell>(_: T.Type) where T: NibLoadable {
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: T.nibName, bundle: bundle)
register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
}
}
public extension UITableView {
func register<T: UITableViewCell>(_: T.Type) {
register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
func register<T: UITableViewCell>(_: T.Type) where T: NibLoadable {
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: T.nibName, bundle: bundle)
register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
}
// MARK: Dequeuing
public extension UICollectionView {
func dequeue<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
}
return cell
}
}
public extension UITableView {
func dequeue<T: UITableViewCell>(for indexPath: IndexPath) -> T {
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