Created
October 17, 2018 19:13
-
-
Save vialyx/07cd43bc17f3f0606bca7f542985c97b 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
protocol ReusableViewType: class { | |
static var defaultReuseIdentifier: String { get } | |
static var nib: UINib { get } | |
} | |
extension ReusableViewType where Self: UIView { | |
static var defaultReuseIdentifier: String { | |
return NSStringFromClass(self) | |
} | |
static var nib: UINib { | |
let bundle = Bundle(for: Self.self) | |
let nibName = NSStringFromClass(self).components(separatedBy: ".").last! | |
let nib = UINib(nibName: nibName, bundle: bundle) | |
return nib | |
} | |
} | |
extension UITableView { | |
func register<T: UITableViewCell>(_: T.Type) where T: ReusableViewType { | |
register(T.nib, forCellReuseIdentifier: T.defaultReuseIdentifier) | |
} | |
} | |
class Cell: UITableViewCell, ReusableViewType {} | |
let tableView = UITableView() | |
// Regular Cell registration | |
tableView.register(UINib(nibName: "Nib", bundle: Bundle.main), forCellReuseIdentifier: "CellIdentifier") | |
// Constrainted generic extension in Action | |
tableView.register(Cell.self) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment