Skip to content

Instantly share code, notes, and snippets.

@ConorBrady
Last active April 25, 2017 16:17
Show Gist options
  • Save ConorBrady/69b3cd46c50f173e833bc5fe619670af to your computer and use it in GitHub Desktop.
Save ConorBrady/69b3cd46c50f173e833bc5fe619670af to your computer and use it in GitHub Desktop.
Generic table view controller
class TableViewController<Cell>: UITableViewController where Cell: UITableViewCell, Cell: HasModel, Cell: HasHeight {
let models: [Cell.Model]
let onSuccess: (Cell.Model, TableViewController<Cell>) -> ()
init(
models: [Cell.Model],
style: UITableViewStyle,
onSuccess: @escaping (Cell.Model, TableViewController<Cell>) -> ()
) {
self.models = models
self.onSuccess = onSuccess
super.init(style: style)
}
override func viewDidLoad() {
tableView.register(Cell.self)
tableView.rowHeight = Cell.height
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return (tableView.dequeueReusableCell() as Cell) <== {
$0.model = models[indexPath.row]
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onSuccess(models[indexPath.row], self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment