ios - 标签背景颜色根据来自服务器的文本更改

标签 ios swift uitableview for-loop uilabel

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

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

并且 (types) 是一个全局声明的变量。

    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
    }

最佳答案

在我看来,问题是因为在循环中,将背景颜色更改为红色后,您会收到另一个不是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
}

关于ios - 标签背景颜色根据来自服务器的文本更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49912932/

相关文章:

换行后 iOS 7.1 UITextView 仍未滚动到光标/插入符号

ios - Interface Builder 错误地调整导航项

ios - 将 NSManagedObject 从一个 View Controller 传递到另一个 View Controller

ios - 如何在 tableView :heightForRowAtIndexPath: be implicitly recursive? 中初始化 NSAttributedString

ios - git 差异 : How to ignore starting space of an empty line?

ios - 如何控制网格类型 View 的滚动

ios - 在 iOS 中使用自动布局,如何将标签定位在其包含 View 高度的 1/3 处?

ios - Swift 3 仅在设备上调试时含糊不清地使用下标

objective-c - 在与 Objective C 项目不同的项目中调用 swift 文件。 Apple Mach-o 链接器错误

iphone - 修改 UITableView 的侧边栏?