标签背景颜色变化根据来自服务器的文本

时间:2018-04-19 04:48:59

标签: ios swift uitableview for-loop uilabel

如果发送(文本),我想根据来自服务器的文本更改标签背景颜色。背景颜色为红色,其他颜色为绿色。

我的for循环工作正常。但是所有标签上的颜色都显示为绿色。

而且(类型)是全局解除变量。

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! HomeCell



    for all in (arrayForType)!
    {
        print(all)
        let types = (all as AnyObject).object(forKey: "type") as! String
        print(types)

       if types == "Send"
        {
            cell.lblForSend.backgroundColor = UIColor.red
        }
        else
        {
            cell.lblForSend.backgroundColor = UIColor.green
        }

    }
    return cell
    }

1 个答案:

答案 0 :(得分:2)

在我看来,问题是因为在循环中,在将背景颜色更改为红色后,您将获得另一个不是Send的文本,它会使您的标签恢复为绿色

您可以尝试以下代码

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

  let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! HomeCell

  let types = (arrayForType[indexPath.row] as AnyObject).object(forKey: "type") as! String

  if types == "Send"
  {
    cell.lblForSend.backgroundColor = UIColor.red
  } else {
    cell.lblForSend.backgroundColor = UIColor.green
  }

  return cell
}
相关问题