我现在正在开发一个应用程序,它需要在我的应用程序的多个场景中使用完全相同的表格 View ,但是,表格的数据和位置会发生变化,如这两张图片所示(表格 View 在红色)
在整个应用程序的所有表格实例中,它应该具有:
- 相同的委托(delegate)方法
- 相同的数据源方法(尽管实际数据会发生变化)
- 具有相同导出和操作的相同表格 View 单元格类型。
- 相同的内部约束(我不想每次都手动为表格单元格添加约束)。
现在我将它们编码为两个单独的 View Controller 中的两个单独的 TableView ,但是,我意识到我需要在我的应用程序的更多地方复制相同的表和逻辑,这并不感觉喜欢正确的方式去做。所以我的问题是,如何在 iOS 中(使用 interface builder 或 swift)以干净、干燥的方式完成满足上述规范的表复制?
最佳答案
如果您想设计一次单元格,然后在不同 View Controller 的不同表格 View 中使用它们,您必须在单独的 .xib 文件中设计它们。原型(prototype)单元是每个 View Controller ,不能很好地缩放。
如果所有数据源和委托(delegate)方法都相同,您可以将此协议(protocol)的实现移至单独的类。您可以使用要显示的项目数组配置此类。
class ReusableTableView: NSObject, UITableViewDataSource, UITableViewDelegate
{
var tableView: UITableView
var tableViewData: [String]
init(_ tv: UITableView, _ data: [String])
{
tableViewData = data
tableView = tv
super.init()
tableView.delegate = self
tableView.dataSource = self
// Register all of your cells
tableView.register(UINib(nibName: "SomeNib", bundle: nil), forCellReuseIdentifier: "example-id")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "example-id", for: indexPath)
}
}
有了这两个构建 block ,您可以在每个 View Controller 上单独布局 TableView ,并将其与可重用的数据源/委托(delegate)连接起来。
class ExampleTablewViewController: UIViewController
{
@IBOutlet weak var tableView: UITableView!
var reusableTableView: ReusableTableView!
override func viewDidLoad() {
super.viewDidLoad()
reusableTableView = ReusableTableView(tableView, ["lorem", "ipsum", "dolor"])
reusableTableView.tableView.reloadData()
}
}
您可以在 GitHub repo 中找到我如何看待这一点的基本示例.
关于ios - 如何在 Swift 的多个 View Controller 中重用 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46898574/