Skip to content

Instantly share code, notes, and snippets.

@geek1706
Last active July 6, 2018 11:12
Show Gist options
  • Select an option

  • Save geek1706/2988528cb931e99b6b70cad0148c7440 to your computer and use it in GitHub Desktop.

Select an option

Save geek1706/2988528cb931e99b6b70cad0148c7440 to your computer and use it in GitHub Desktop.
Reusable View Protocols for UITableView swift 4
protocol ReusableView: class {}
extension ReusableView where Self: UIView {
static var reuseIdentifier: String {
return String(describing: self)
}
}
protocol NibLoadableView: class {}
extension NibLoadableView where Self: UIView {
static var nibName: String {
return String(describing: self)
}
}
extension UITableViewCell: ReusableView {}
extension UITableViewHeaderFooterView: ReusableView {}
extension UITableView {
func register<T: UITableViewCell>(_: T.Type) {
register(T.classForCoder(), forCellReuseIdentifier: T.reuseIdentifier)
}
func register<T: UITableViewCell & NibLoadableView>(_: T.Type) {
let nib = UINib(nibName: T.nibName, bundle: nil)
register(nib, forCellReuseIdentifier: T.reuseIdentifier)
}
func register<T: UITableViewHeaderFooterView & NibLoadableView>(_: T.Type) {
let nib = UINib(nibName: T.nibName, bundle: nil)
register(nib, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Unable to dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
func dequeueReusableCell<T: UITableViewCell>() -> T {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier) as? T else {
fatalError("Unable to dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>() -> T {
guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) as? T else {
fatalError("Unable to dequeue view with identifier: \(T.reuseIdentifier)")
}
return headerFooterView
}
}
extension UITableView {
func hideEmptyCells() {
tableFooterView = UIView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment