2017-11-11 81 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  
}