2016-10-16 26 views
2

我的項目中有一個UITableView控制器。所以我做了一個UITableViewCell設置喜歡這裏:UITableViewCell的背景設置在滾動上重置

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

    cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)." 

    if indexPath.row % 2 == 1 { 
     cell.backgroundColor = UIColor.gray 
    } 

    return cell 
} 

我希望我的tableview的細胞是灰色的,如果他們的指數是不是整除2.

時出現的tableview,一切都是完美的!但是當我上下滾動時,單元格開始將它們的顏色變成灰色。

所以最後我的所有細胞都是灰色的。

下面是一些圖片:

before

after

回答

3

嘗試添加else聲明,因爲細胞被重用。

else { 
    cell.backgroundColor = UIColor.white 
} 
+0

非常感謝)它是那麼容易!):d –

+0

@AlexVihlayev沒問題的伴侶。 :) –

0

因爲tableview中重用細胞

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)." 

if indexPath.row % 2 == 1 { 
    cell.backgroundColor = UIColor.gray 
}else{ 
    cell.backgroundColor = YOUR_COLOR 
} 
return cell 

}

編輯:蓋勒特李回答了第一和相當簡單

2

的問題是,你永遠不設置背景回白色。由於單元格正在被重用,因此在某些時候,您將所有單元格設置爲灰色。相反,你應該檢查該行指數每次細胞被重用:

cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.white : UIColor.gray 
相關問題