在访问外面的单元格时获得nil

时间:2017-12-15 10:38:23

标签: ios uitableview swift3

以下是我的代码,我在我的函数中访问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

    }
}

2 个答案:

答案 0 :(得分:0)

最后通过传递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

}

答案 1 :(得分:-3)

使用dequeueReusableCell

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