为了实现可与泛型一起重用的 BaseTableViewController,我阅读了一些很棒的文章。
它正在工作,这是一个简单的例子:
if let mountains = viewModel?.model["mountain"] as? ResponseMountain {
let mountainTableViewController = BaseTableViewController(items: mountains.result, config: { (cell, item) in
cell.textLabel?.text = item.name
}, style: .plain)
mountainTableViewController.title = "Mountains"
self.navigationController?.pushViewController(mountainTableViewController, animated: true)
}
假设我想显示我所在国家/地区的一个简单的山脉列表,当您选择一个山脉时,您会显示该山脉内所有可用地 block 的列表。
这就是为什么我想重用相同的 TableViewController,但使用不同的数据。
我不知道如何用我的泛型实现来处理它。
这是我目前的实现:
final class BaseTableViewController<Item>: UITableViewController {
var items: [Item] {
didSet {
tableView.reloadData()
}
}
let config: (UITableViewCell, Item) -> ()
init(items: [Item], config: @escaping (UITableViewCell, Item) -> (), style: UITableViewStyle) {
self.items = items
self.config = config
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cellIdentifier")
cell.textLabel?.textColor = UIColor.white
let item = items[indexPath.row]
config(cell, item)
return cell
}
}
它高效、简单,适用于不同的用例。
但我如何使用泛型实现自定义 didSelectRowAt
,以便使用我刚刚选择的行中的数据推送同一 BaseViewController 的实例?
最佳答案
我会按照您处理 cellForRowAtIndexPath
的方式进行操作。将类型为 (Item) -> ()
的另一个闭包传递给 init
。然后在 didSelectRowAt
中调用该闭包并传递所选项目。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = items[indexPath.row]
didSelect(item)
}
关于swift - iOS - 通过泛型重用相同的 TableViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51616930/