自定义 table 单元格 class 在 cellForRowAt 中不起作用

Custom table cell class not working in cellForRowAt

这个问题让我抓狂了 3 天。我创建了一个自定义单元格 class:

class TransitoPalinaTableViewCell: UITableViewCell {

@IBOutlet weak var lblOrario: UILabel!
@IBOutlet weak var lblDestinazione: UILabel!
@IBOutlet weak var lblNote: UILabel!
@IBOutlet weak var lblBus: UILabel!

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

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

    // Configure the view for the selected state
}

}

在我的视图控制器中我有这个:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TransitoPalinaTableViewCell

    // Configure the cell...
    let hour = Int(self.transito.listaCorse[indexPath.row].tempoTransito) / 3600
    let mins = Int(self.transito.listaCorse[indexPath.row].tempoTransito % 3600) / 60

    cell.lblOrario?.text = String(format: "%02d:%02d", hour, mins)
    cell.lblDestinazione?.text = self.transito.listaCorse[indexPath.row].arrivoCorsa
    cell.lblNote?.text = ""
    cell.lblBus?.text = self.transito.listaCorse[indexPath.row].automezzo


    cell.backgroundColor = UIColor.init(red: 0, green: 60/255, blue: 113/255, alpha: 1)

    return cell
}

在情节提要中,我设置了 table 视图单元格标识符:"Cell" 和自定义 Class "TransitoPalinaTableViewCell".

问题是当调用 cellForRowAt 时出现错误

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

在 dequeueReusableCell 命令行。

正如我在其他帖子中读到的那样,我没有放线 self.tableView.register(TransitoPalinaTableViewCell.self, forCellReuseIdentifier: "Cell") 在 vi​​ewdidLoad() 中 - 它会创建一个全新的单元模型,不与情节提要中的插座连接。 我尝试再次创建 TransitoPalinaTableViewCell class 及其出口,但没有任何改变。

感谢任何帮助。

您可以使用单元格 class 或单元格 nib 注册单元格。

tableView.register(UINib(name: "YourNibName", bundle: nil), forCellReuseIdentifier: "Cell")

但这只有在您在 Xib 文件中创建单元格时才有效。如果它是在 Storyboard 中创建的,那么恐怕无法在您创建它的 ViewController 以外的任何地方使用该单元格。

我使用 .xib 文件创建了一个新的 CustomTableViewCell class,并使用该文件将插座与 class 连接起来。我在 xib 文件的属性检查器中将 customCell 设置为标识符,并从 table 视图控制器中的情节提要中删除了任何其他标识符。

在 viewDidLoad 中,我这样注册了 Cell:

let cellNib = UINib.init(nibName: "CustomTableViewCell", bundle: nil)
self.tableView.register(cellNib, forCellReuseIdentifier: "customCell")

我在 cellForRowAt 中使用了

let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableViewCell