如何在索引路径的行的单元格中显示数据模型内容?

How to Display data model content in cell for row at indexpath?

enter image description herehttps://i.stack.imgur.com/pRZu5.png 您好我正在尝试在表格视图中显示特定对象的名称和 pointsWorth。但是 xcode 回答 missionTitleLabel 不能用于 missionCell。是否可以显示我创建的对象的信息?

感谢能得到的任何帮助!

这是我的代码: MasterViewController.swift:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath)
    let event = self.fetchedResultsController.object(at: indexPath)
    self.configureCell(cell, withEvent: event)

    let mission = missions[indexPath.row]
    MissionCell.missionTitleLabel?.text = mission

    return cell   
}

示例数据模型:

枚举类别枚举{ 案例一 案例二 案例三 案例d } public class 任务 {

var name: String
var pointsWorth: Int
var colorTheme: UIColor
var description: String
var category: CategoryEnum

init(name: String, pointsWorth: Int, colorTheme: UIColor, description: String, category: CategoryEnum) {
    self.name = name
    self.pointsWorth = pointsWorth
    self.colorTheme = colorTheme
    self.description = description
    self.category = category
}

} let mission1 = Mission(name: "a", pointsWorth: 50, colorTheme: .blue, description: "a is the fist letter in the alphabet", category:.a)

let mission2 = Mission(name: "b", pointsWorth: 60, colorTheme: .red, description: "b is the second letter in the alphabet", category:.b)

var missions: [Mission] = [mission1, mission2]

MissionCell.swift:

import UIKit

class 任务单元格:UITableViewCell {

@IBOutlet weak var missionTitleLabel: UILabel!
@IBOutlet weak var missionPointLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

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

}

}

您应该像这样分配值:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as! MissionCell
    let event = self.fetchedResultsController.object(at: indexPath)
    self.configureCell(cell, withEvent: event)

    let mission = missions[indexPath.row]
    cell.missionTitleLabel?.text = mission.name


    return cell   
}

请记住,只有当您确定存在一种单元格类型时,才能使用对 MissionCell 的强制转换,否则您会崩溃。 考虑:

if let cell = cell as? MissionCell {
  cell.missionTitleLabel?.text = mission.name

}

这里你应该使用 cell 变量作为 MissionCell.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as! MissionCell
   let event = self.fetchedResultsController.object(at: indexPath)
   self.configureCell(cell, withEvent: event)

   let mission = missions[indexPath.row]
   cell.missionTitleLabel?.text = mission.name

   return cell   
}

希望对您有所帮助。