Created
March 31, 2015 13:21
-
-
Save darren102/779341c00f13d5e76cac 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
import UIKit | |
class DTFBaseTypedTableViewController<T>: UIViewController { | |
private lazy var tableView: UITableView = { | |
let tableView = UITableView() | |
tableView.setTranslatesAutoresizingMaskIntoConstraints(false) | |
tableView.dataSource = self | |
tableView.delegate = self | |
return tableView | |
}() | |
var items: [T] = [] { | |
didSet { self.tableView.reloadData() } | |
} | |
var configureCell: (UITableViewCell, T) -> () = { _ in () } | |
var didSelectRow: (NSIndexPath, T) -> () = { _ in () } | |
required init(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.addSubview(tableView) | |
let views = ["tableView" : tableView] | |
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat( | |
"|[tableView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)) | |
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat( | |
"V:[tableView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)) | |
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") | |
} | |
} | |
// MARK: - UITableViewDatasource | |
extension DTFBaseTypedTableViewController : UITableViewDataSource { | |
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return items.count | |
} | |
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell | |
configureCell(cell, items[indexPath.row]) | |
return cell | |
} | |
} | |
// MARK: - UITableViewDelegate | |
extension DTFBaseTypedTableViewController : UITableViewDelegate { | |
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { | |
let item: T = items[indexPath.row] | |
didSelectRow(indexPath, item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment