Skip to content

Instantly share code, notes, and snippets.

@vialyx
Created October 17, 2018 19:13
Show Gist options
  • Save vialyx/07cd43bc17f3f0606bca7f542985c97b to your computer and use it in GitHub Desktop.
Save vialyx/07cd43bc17f3f0606bca7f542985c97b to your computer and use it in GitHub Desktop.
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