Last active
November 3, 2017 04:11
-
-
Save lawreyios/b15d243bb4669fecea07587d59af1d9f to your computer and use it in GitHub Desktop.
This file contains 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
//: Playground - noun: a place where people can play | |
import UIKit | |
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) | |
} | |
} | |
class FancyTableViewCell: UITableViewCell, ReusableView, NibLoadableView { } | |
extension UITableView { | |
func register<T: UITableViewCell & ReusableView & NibLoadableView>(_: T.Type) { | |
let nib = UINib(nibName: T.nibName, bundle: nil) | |
register(nib, forCellReuseIdentifier: T.reuseIdentifier) | |
} | |
func dequeueReusableCell<T: UITableViewCell & ReusableView>(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 | |
} | |
} | |
class TableViewController: UITableViewController { | |
override func viewDidLoad() { | |
tableView.register(FancyTableViewCell.self) | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as FancyTableViewCell | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment