在Swift中将TableView引导到MVC



现在我得到了单元格的所有数据:

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 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)
}

}

但是我不知道该怎么做,因为"索引路径"换句话说,我只允许在tableView的函数中使用。有人能告诉我,如何做正确的,导致MVC,请

您的第一个代码片段并没有什么真正的问题,除了在局部变量中捕获RealmModel.shared.getSections()[indexPath.section].items[indexPath.row]可能比执行两次索引更好。

如果您想要将代码移动到单元格中,您可以将Realm对象传递给单元格类中的函数。您还没有提供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这样的属性名应该以小写字母开头,我已经在代码中做了这个更改。

最新更新