Created
October 4, 2017 06:58
-
-
Save ts95/414e0e26ec782189fdfaaefe2230f93a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import UIKit | |
protocol ReusableView: class { | |
static var defaultReuseIdentifier: String { get } | |
} | |
extension ReusableView where Self: UIView { | |
static var defaultReuseIdentifier: 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).components(separatedBy: ".").last! | |
} | |
} | |
extension UITableViewCell: ReusableView { } | |
extension UITableView { | |
func register<T: UITableViewCell>(_: T.Type) { | |
register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) | |
} | |
func register<T: UITableViewCell>(_: T.Type) where T: NibLoadableView { | |
let bundle = Bundle(for: T.self) | |
let nib = UINib(nibName: T.nibName, bundle: bundle) | |
register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) | |
} | |
func dequeueReusableCell<T: UITableViewCell>(forIndexPath 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 | |
} | |
} | |
extension UICollectionViewCell: ReusableView { } | |
extension UICollectionView { | |
func register<T: UICollectionViewCell>(_: T.Type) { | |
register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) | |
} | |
func register<T: UICollectionViewCell>(_: T.Type) where T: NibLoadableView { | |
let bundle = Bundle(for: T.self) | |
let nib = UINib(nibName: T.nibName, bundle: bundle) | |
register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) | |
} | |
func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment