使用if语句更改单元格中Label的文本颜色

问题描述 投票:0回答:1

如果alarmLevel!=“0”的值,我正在尝试更改单元格中标签(或标签)的颜色。这是我到目前为止所做的,它改变了所有单元格中cell.locationLabel的颜色,而不仅仅是满足if语句的颜色。我确定它与indexPath有关,但我无法弄明白。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = myTableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! ViewControllerTableViewCell
    cell.locationLabel.text = eventsList[indexPath.row].location
    cell.eventTimeLabel.text = eventsList[indexPath.row].dateTime
    cell.eventTypeLabel.text = eventsList[indexPath.row].agencyEventSubtypeCode
    cell.agencyIdLabel.text = eventsList[indexPath.row].agencyId

    if alarmLevel != "0" {
      cell.locationLabel.textColor = UIColor.red
    } else {
      cell.locationLabel.textColor = UIColor.black
    }
    return cell
}
ios swift
1个回答
0
投票

您需要将alarmLevel作为整数变量添加到事件列表数组类型中。并根据您对数组event中每个eventsList项的需要更改此整数值

class Events {
    var location = String()
    var dateTime = String()
    var agencyEventSubtypeCode = Int()
    var agencyId = Int()
    var alarmLevel = Int() //Need this here
}

var eventsList = [Events]()

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

let cell = myTableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! ViewControllerTableViewCell
cell.locationLabel.text = eventsList[indexPath.row].location
cell.eventTimeLabel.text = eventsList[indexPath.row].dateTime
cell.eventTypeLabel.text = ("\(eventsList[indexPath.row].agencyEventSubtypeCode)")
cell.agencyIdLabel.text = ("\(eventsList[indexPath.row].agencyId)")

if eventsList[indexPath.row].alarmLevel != 0 {
  cell.locationLabel.textColor = UIColor.red
} else {
  cell.locationLabel.textColor = UIColor.black
}
return cell
}
© www.soinside.com 2019 - 2024. All rights reserved.