我已经阅读了一些帖子,但我找不到这个问题的明确答案:在MVC框架中,谁应该负责UI的设置?我在两个选项之间取得平衡:
class ViewController: UITableViewController {
private var users: [User]
...
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = dequeueDataCell(id: "myCell") as? CellView else { return UITableViewCell() }
cell.title.text = user?.name
cell.subtitle.text = user?.nickname
cell.action.isHidden = isSelected
// other numerous UI set up on the cell
return cell
}
}
class CellView: UITableViewCell {
@IBOutlet weak var title: UILabel?
@IBOutlet weak var subtitle: UILabel?
@IBOutlet weak var action: UIButton!
}
和
class ViewController: UITableViewController {
private var users: [User]
...
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = dequeueDataCell(id: "myCell") as? CellView else { return UITableViewCell() }
cell.user = self.users[indexPath.row]
cell.isSelected = false
cell.refresh()
return cell
}
}
class CellView: UITableViewCell {
@IBOutlet private weak var title: UILabel?
@IBOutlet private weak var subtitle: UILabel?
@IBOutlet private weak var action: UIButton!
weak var user: User?
var isSelected = false
func refresh() {
title.text = user?.name
subtitle.text = user?.nickname
action.isHidden = isSelected
// other numerous UI set up on the cell
}
}
到目前为止,我一直在使用大多数iOS教程中的第一种方法。但是我发现这使得UIViewController更长,而它们已经变得漫长而模糊,并且因为它混合了UI和状态逻辑而更难阅读。