在外部访问单元格时得到 nil

Getting nil while accessing cell outside

下面是我的代码,我在我的函数中访问 cell,但我得到 nil

 private func setDataForStatusLabel(stausText: String, statusColor: UIColor) {

    let indexPath = IndexPath(row: 0, section: 0)
    let cell = tableView.cellForRow(at: indexPath) as? CustomLocateVehicleCell

    if let cell = cell {
        cell.statusLabel.text = stausText
        cell.containerStatusLabel.text = stausText
        cell.statusLabel.textColor = statusColor
        cell.containerStatusLabel.textColor = statusColor
        cell.statusColorView.backgroundColor = statusColor
        cell.containerStatusColorView.backgroundColor = statusColor

    }
}

使用 dequeueReusableCell

let cell = tblView.dequeueReusableCell(withIdentifier: "CustomLocateVehicleCell") as! CustomLocateVehicleCell
cell.configureCell(stausText, statusColor)
  1. 但在此之前,请确保将 UITableViewCell 拖放到 UITableView 上
  2. 使用 CustomLocateVehicleCell
  3. 更改单元格的 class
  4. 设置标识符 CustomLocateVehicleCell
  5. configureCell 在 CustomLocateVehicleCell 中创建此方法,并在管理单元格的颜色和文本的位置编写代码

终于通过传递cell参数解决了问题

private func setDataForStatusLabel(stausText: String, statusColor: UIColor, cell: CustomLocateVehicleCell) {

    cell.statusLabel.text = stausText
    cell.containerStatusLabel.text = stausText
    cell.statusLabel.textColor = statusColor
    cell.containerStatusLabel.textColor = statusColor
    cell.statusColorView.backgroundColor = statusColor
    cell.containerStatusColorView.backgroundColor = statusColor

}