如果 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/