在 Swift 中将 TableView 引入 MVC

Leading TableView to MVC in Swift

现在我像这样获取单元格的所有数据:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TVCellTableViewCell
    
    cell.comeTypeLabel.text = "Writing off"
    cell.amountLabelCell.text =  String(RealmModel.shared.getSections()[indexPath.section].items[indexPath.row].Amount)
    if RealmModel.shared.getSections()[indexPath.section].items[indexPath.row].category != "" {
        cell.labelCell.text = RealmModel.shared.getSections()[indexPath.section].items[indexPath.row].category
    } else {
        cell.labelCell.text = "Income"
        cell.comeTypeLabel.text = ""
    }
    return cell
}

它有效,但我需要引导我的项目使用 MVC。所以,据我所知,我需要在单元格 class:

中编写所有逻辑
class TVCellTableViewCell: UITableViewCell {
@IBOutlet weak var labelCell: UILabel!
@IBOutlet weak var amountLabelCell: UILabel!
@IBOutlet weak var comeTypeLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    labelCell.font = UIFont(name: "Gill Sans SemiBold", size: 20)
    labelCell.textColor = UIColor.black
    amountLabelCell.font = UIFont(name: "Gill Sans SemiBold", size: 20)
    amountLabelCell.textColor = UIColor.black
    comeTypeLabel.font = UIFont(name: "Gill Sans SemiBold", size: 18)
    comeTypeLabel.textColor = UIColor.gray
    
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

}

但我不知道该怎么做,因为我使用的“indexpathes”和其他词只允许在 tableView 的函数中使用。 有人可以告诉我如何做正确并导致 MVC,拜托

您的第一个代码段没有任何问题,只是在局部变量中捕获 RealmModel.shared.getSections()[indexPath.section].items[indexPath.row] 可能比执行两次索引更好。

如果您想将代码移动到单元格中,可以将 Realm 对象传递给单元格中的函数 class。您还没有提供 Realm 模型对象的类型,所以我将使用 Item。你会有这样的东西:

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

    let item = RealmModel.shared.getSections()[indexPath.section].items[indexPath.row]
    cell.configure(with: item)
     
    return cell
}

class TVCellTableViewCell: UITableViewCell {

//... existing code
    func configure(with item:Item) {
        if item.category.isEmpty {
            self.comeTypeLabel.text = ""
            self.labelCell.text = "Income"
        } else {
            self.comeTypeLabel.text = "Writing off"
            self.labelCell.text = item.category
        }
        self.amountLabelCell.text = String(item.amount)
     }
}

请注意,按照惯例 属性 名称,如 amount 应以小写字母开头,我已在代码中进行此更改。