Skip to content

Instantly share code, notes, and snippets.

@NikhilManapure
Created December 15, 2018 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikhilManapure/d82be13709ef0d9e8bcc49d4a6dbe90a to your computer and use it in GitHub Desktop.
Save NikhilManapure/d82be13709ef0d9e8bcc49d4a6dbe90a to your computer and use it in GitHub Desktop.
import Foundation
protocol ReusableView: class {
static var identifier: String { get }
}
extension ReusableView where Self: UIView {
static var identifier: String {
return String(describing: self)
}
}
protocol NibLoadableView: class {
static var nibName: String { get }
}
extension NibLoadableView where Self: UIView {
static var nibName: String {
return String(describing: self)
}
}
extension UICollectionView {
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView {
register(T.self, forCellWithReuseIdentifier: T.identifier)
}
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: T.nibName, bundle: bundle)
register(nib, forCellWithReuseIdentifier: T.identifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.identifier)")
}
return cell
}
}
extension UITableView {
func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: T.nibName, bundle: bundle)
register(nib, forCellReuseIdentifier: T.identifier)
}
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.identifier)")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment