2016-03-20 171 views
0

我無法更改tableView中偶數單元格的背景顏色。加載視圖時,單元格着色正確,但在滾動時,背景顏色變爲白色或全淺灰色。更改tableView中偶數單元格的背景顏色

我應該以另一種方式更新背景顏色嗎?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("gradeCell", forIndexPath: indexPath) 

    if (indexPath.row % 2 == 0) { 
     cell.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0) 
    } 
    return cell 
} 
+4

如果該行甚至不是 – dan

+0

或者在'prepareForReuse'中,您需要將背景顏色設置回原來的顏色。 – nhgrif

+0

謝謝,忘記了單元格正在被重用 – Bob

回答

3

把這個代碼片段。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("gradeCell", forIndexPath: indexPath) 

    if (indexPath.row % 2 == 0) { 
     cell.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0) 
    }else{ 
     cell.backgroundColor = UIColor.whiteColor() // set your default color 
    } 

    return cell 
    } 
相關問題