如果Send(text(即将到来,我想根据来自服务器的文本更改标签背景颜色。背景颜色将为红色,其他将为绿色。
我的 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
}
在我看来,问题是因为在循环中,将背景颜色更改为红色后,您会得到另一个未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
}