2017-02-20 89 views
0

我有一個UITableView,當用戶點擊一個單元格時它會變成灰色,表明它已完成。但是,當單元格滾動出視圖時,當它返回到視圖中時,它已返回到其默認背景色,從而擦除用戶交互。堅持UITableViewCell滾動tableViewCells背景顏色

有沒有辦法在滾動時保持單元格點擊的背景顏色?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? TodaysRoutineTableViewCell else { 
     fatalError("Unexpected Index Path") 
    } 
    cell.backgroundColor = UIColor.customBackgroundGraphite() 
    cell.textLabel?.textColor = UIColor.white 
    configure(cell, at: indexPath) 
    return cell 
} 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

    if let cell = tableView.cellForRow(at: indexPath) { 

     if cell.backgroundColor == UIColor.customExerciseDoneCellColor() { 
      cell.backgroundColor = UIColor.customBackgroundGraphite() 
     } else if cell.backgroundColor == UIColor.customBackgroundGraphite() { 
      cell.backgroundColor = UIColor.customExerciseDoneCellColor() 
     } 
    } 
} 
+0

保持你的模型類的狀態和使用模型類填充單元格。將視圖與模型分開。 – NSNoob

+0

您正在重複使用帶有'tableView.dequeueReusableCell'的單元格。這意味着相同的單元格將被重新用於在滾動/重新加載時顯示不同的數據。除非您提供該信息,否則您認爲重複使用的細胞是如何記住的? – NSNoob

+0

我知道這是問題,即時在這裏尋找解決方案... – jwarris91

回答

-2

問題是當您在選擇單元格後滾動時,所選顏色不會被保留嗎?

行代表的單元格在您滾動時被調用。因此,即使您在Background中設置了背景,也會在調用Cell的行時選擇它的更改。

爲了解決這種情況,添加一個布爾值到tableview單元格,當您選擇單元格更改布爾狀態。

在單元格爲行補充一點:

if cell.CheckBoolean == true{ 
    cell.backgroundcolor = UI.color() 
}else{ 
    cell.backgroungcolor = UI.color() 
} 

在沒有選擇委託: 改變布爾值並重新加載表視圖

+0

在OP我已經表明這是問題,尋找解決方案... – jwarris91

+0

SahyadriChava,我編輯了答案,希望這可以是解決方案。 – Anuraj