ios - 处理数据和 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...
}
所以问题是:
- 什么是更好的方法,或者两种情况都可以?
- 是不是认为我们在第二种方式中传递数据给视图?
- 我是否正确,万一我们有被动的观点,但万一不是?
解决方案
它们的工作原理相同,但在protocol
,
1-重用于其他细胞。
2-整体更整洁cellForRowAt
。
3-将来会稍微快一点,因为您直接与函数交谈而不是直接访问@IBOutlets
和编辑它,这会导致错误百分比最小,因为您仅限于protocol
.
4-您可以使用它而根本不必创建单元格,当您只想快速创建所有内容UIViewController
然后创建自定义单元格时,这很好。
问题 2:
将数据传递到单元格对于干净的代码非常有用,因为您可以创建尽可能多的多态函数来将数据直接处理到单元格中,而不是if else
在func cellForRowAt
.
例如:
protocol configurable {
func configure(dataForm: SomeObject)
func configure(dataForm: SomeOtherObject)
}
问题 3:
被动视图。将具有所有应用程序特定行为的屏幕和组件提取到控制器中,以便小部件的状态完全由控制器控制。
他们都是被动的。
推荐阅读
- html - 当高度低于内容大小时,为什么会裁剪 div 内的绝对定位内容?
- r - 如何使用 facet_wrap 在 R 中绘制多个位置点?
- rust - Rust:条件特征继承
- python-3.x - 如何获得对消息做出反应的用户?
- bash - 替换bash中两个括号之间的空格和/
- sqlite - 为什么我不能使用命令行创建这个 SQLite 视图?
- python - 如何从包含 API 字典的列表中获取值
- java - 编辑长文本 TextView 会导致辅助功能代码中出现“FAILED BINDER TRANSACTION”错误
- r - 折叠包:对两个向量求和,但保留空交叉点
- java - E/Volley:[6074] BasicNetwork.performRequest:意外响应代码 403