ios - 如何在 Swift 的多个 View Controller 中重用 TableView ?

标签 ios swift xcode uitableview interface-builder

我现在正在开发一个应用程序,它需要在我的应用程序的多个场景中使用完全相同的表格 View ,但是,表格的数据和位置会发生变化,如这两张图片所示(表格 View 在红色)

enter image description here

enter image description here

在整个应用程序的所有表格实例中,它应该具有:

  1. 相同的委托(delegate)方法
  2. 相同的数据源方法(尽管实际数据会发生变化)
  3. 具有相同导出和操作的相同表格 View 单元格类型。
  4. 相同的内部约束(我不想每次都手动为表格单元格添加约束)。

现在我将它们编码为两个单独的 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/

相关文章:

ios - 无法使用纵向模式获得横向图像选择器工作

ios - 处理连接到 Web 服务的 native 应用程序的登录功能

ios - 使用未声明的类型 'NSXMLElement' 错误

iphone - 当键盘出现时启用 ScrollView

swift - 在swift中计算从单词到字符串结尾的字符串范围

objective-c - 如何在 UICollectionViewLayout 和 UIViewController 之间传递数据

ios - Xcode mach -o 链接器

c++ - 如何使用 coreAudio 将标准化浮点值数组写入 AIFF?

iphone - sqlite3_exec != SQLITE_OK

ios - 在 Xamarin 中生成适用于 IOS 的 PDF