2017-11-11 75 views
2

我想为单个TableViewCell着色,并且在开始时它可以正常工作,但随后它只会弄脏并且颜色也会随着其他随机单元格着色。Xcode UITableView单元格背景不起作用

我要离开代码和一些截图,希望你能帮上忙。我正在使用Xcode 9和Swift 4.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Linea", for: indexPath) 
    cell.textLabel?.text = ListaLineas[indexPath.row] 
    if (cell.textLabel?.text == "TifloInnova"){ 
     cell.textLabel?.textColor = UIColor(red: 100, green: 100, blue: 100, alpha: 1) 
     cell.contentView.backgroundColor = UIColor(red:100.0, green: 0.0, blue:0.0, alpha:0.8) 
    } 
    else{ 
     cell.textLabel?.textColor = UIColor(red: 0.0, green: 0.478, blue: 1, alpha: 1.0) 
    } 
    cell.textLabel?.numberOfLines = 6 
    cell.textLabel?.font.withSize(15) 
    cell.textLabel?.textAlignment = .center 
    cell.textLabel?.lineBreakMode = .byWordWrapping 

    tableView.estimatedRowHeight = 80 
    tableView.rowHeight = UITableViewAutomaticDimension 

    return cell; 
} 

非常感谢。 I want it to looks like this

But sometimes it looks like this

回答

1

对你的情况的解决方案是确保如果单元格文本标签不“TifloInnova”将颜色返回到默认值。你可以执行它如下:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Linea", for: indexPath) 
     cell.textLabel?.text = ListaLineas[indexPath.row] 

     if (cell.textLabel?.text == "TifloInnova"){ 
      cell.textLabel?.textColor = UIColor(red: 100, green: 100, blue: 100, alpha: 1) 
      cell.contentView.backgroundColor = UIColor(red:100.0, green: 0.0, blue:0.0, alpha:0.8) 
     }else{ 
      cell.textLabel?.textColor = UIColor(red: 0.0, green: 0.478, blue: 1, alpha: 1.0) 
      // here what you should add, for instance the default color should be white: 
      cell.contentView.backgroundColor = UIColor.white 
     } 
     cell.textLabel?.numberOfLines = 6 
     cell.textLabel?.font.withSize(15) 
     cell.textLabel?.textAlignment = .center 
     cell.textLabel?.lineBreakMode = .byWordWrapping 

     tableView.estimatedRowHeight = 80 
     tableView.rowHeight = UITableViewAutomaticDimension 

     // btw no need for the ";" :) 
     return cell 
} 
+0

是的,这是问题所在。我没有想到这个解决方案。非常感谢! –

1

您可以重置背景颜色中的“其他”分支,这样做:

if cell.textLabel?.text == "TifloInnova" { 
    cell.contentView.backgroundColor = UIColor.red 
} else { 
    cell.contentView.backgroundColor = UIColor.clear  
}