首页 > 解决方案 > 处理数据和 UITableViewCell 的更好方法是什么?

问题描述

我想了解构建应用架构的正确方法。我读了很多。我面临着两种不同的方法。而且每种方法的流行度似乎都是五十五十。

第一个- 使用 ViewController 或 TableViewController 中的数据配置单元格

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! TableViewCell

    cell.title.text = "Some text"
    // config other data...

    return cell
}

第二个- 通过协议配置单元

protocol SomeCellProtocol {
    func setTitle(text: String)
}

class SomeCell: UITableViewCell {

    @IBOutlet weak var title: UILabel!    
}

extension SomeCell: SomeCellProtocol {

    func setTitle(text: String) {
        title.text = text
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! TableViewCell

    cell.setTitle(text: "Some text")
    // config other data...

}

所以问题是:

标签: iosswiftuitableviewuiviewcontroller

解决方案


它们的工作原理相同,但在protocol,

1-重用于其他细胞。

2-整体更整洁cellForRowAt

3-将来会稍微快一点,因为您直接与函数交谈而不是直接访问@IBOutlets和编辑它,这会导致错误百分比最小,因为您仅限于protocol.

4-您可以使用它而根本不必创建单元格,当您只想快速创建所有内容UIViewController然后创建自定义单元格时,这很好。

问题 2: 将数据传递到单元格对于干净的代码非常有用,因为您可以创建尽可能多的多态函数来将数据直接处理到单元格中,而不是if elsefunc cellForRowAt.

例如:

protocol configurable {
 func configure(dataForm: SomeObject)
 func configure(dataForm: SomeOtherObject)
}

问题 3:

被动视图。将具有所有应用程序特定行为的屏幕和组件提取到控制器中,以便小部件的状态完全由控制器控制。

他们都是被动的。


推荐阅读