Skip to content

Instantly share code, notes, and snippets.

@darren102
Created March 31, 2015 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darren102/779341c00f13d5e76cac to your computer and use it in GitHub Desktop.
Save darren102/779341c00f13d5e76cac to your computer and use it in GitHub Desktop.
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