Last active
May 25, 2019 16:27
-
-
Save Bellaposa/6e18813a314a40f6baff8c7e9a1f99d2 to your computer and use it in GitHub Desktop.
GenericTableViewController Swift
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 GenericTableViewCell<U>: UITableViewCell { | |
var item: U! | |
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { | |
super.init(style: .subtitle, reuseIdentifier: nil) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
} |
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 GenericTableViewController<T, Cell: UITableViewCell>: UITableViewController { | |
var handler: (T) -> () = { _ in } | |
var configure: (Cell, T) -> () | |
var items: [T] | |
private let identifier = "Cell" | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init: has not been implemented") | |
} | |
init(items: [T], configure: @escaping (Cell, T) -> ()) { | |
self.configure = configure | |
self.items = items | |
super.init(style: .plain) | |
self.tableView.register(Cell.self, forCellReuseIdentifier: identifier) | |
} | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return items.count | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! Cell | |
let item = items[indexPath.row] | |
configure(cell, item) | |
return cell | |
} | |
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
tableView.deselectRow(at: indexPath, animated: true) | |
handler(items[indexPath.row]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment