2015-10-07 182 views
1

所以我的實際問題更強健一點。我很好奇是否可以通過編程方式更改單元格的背景顏色,但是它將基於單元格是第一個還是第二個等。我將如何以編程方式更改單元格的背景顏色

我不確定這是甚至可能的,但是什麼我試圖實現的是利用細胞的梯度效應,因爲它們數量增加。

if (indexPath.row % 2) 
    { 
     cell.contentView.backgroundColor = UIColor.redColor() 
    } 
    else 
    { 
     cell.contentView.backgroundColor = UIColor.blueColor() 
    } 

我試過類似的東西,至少有顏色替代看看我是否可以找出接下來做什麼,但這已失敗。交替似乎不是正確的選擇,但它可能是開始編程我想要發生的正確方法。

+0

是的,它很簡單。你試過了嗎?你有什麼問題? – rmaddy

+0

我試過在indexPath.row上使用if語句,但我不確定是否正確。我真的很茫然。我很高興聽到它簡單但是。 –

+0

用你試過的東西更新你的問題。 – rmaddy

回答

6

tableView發送它使用細胞來繪製一排,從而允許委託其顯示之前定製單元格對象之前這個消息給它的代理。 for more info

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    if indexPath.row % 2 == 0 { 
     cell.backgroundColor = UIColor.redColor() 
    } 
    else { 
     cell.backgroundColor = UIColor.blueColor() 
    } 
    return cell 
} 
+0

那麼僅限於兩種顏色的交替?我可以使用3或4嗎? –

+1

你可以用任何你想要的顏色來做這些顏色。答案只是反映你的代碼。但根據索引路徑做任何你需要的。 – rmaddy

+0

你可以根據你的要求使用@JamesChen –

0

是的,可以通過編程方式改變單元格的背景顏色,根據單元格是第一還是第二等。在cellForRowAtIndexPath委託方法中,檢查行是否爲奇數,然後放入不同的背景顏色if它甚至會呈現不同的顏色。通過使用下面的代碼,您將獲得行的替代顏色。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentTableCellIdentifier"]; 
    cell.textLabel.text = @"Your text goes here"; 
    if(indexPath.row % 2 == 0) 
     cell.backgroundColor = [UIColor redColor]; 
    else 
     cell.backgroundColor = [UIColor greenColor]; 
    return cell; 
} 

SWIFT: -

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? { 
    // Configure the cell... 
    let cellId: NSString = "Cell" 
    var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell 

    cell.textLabel.text = "Your text goes here" 
    if(indexPath.row % 2 == 0) 
    { 
     cell.backgroundColor = UIColor.redColor() 
    } 
    else 
    { 
     cell.backgroundColor = UIColor.greenColor() 
    } 
    return cell 
} 
+0

需要在'willDisplayCell:forRowAtIndexPath'方法中設置背景顏色,而不是'cellForRowAtIndexPath'方法。這個問題被標記爲Swift,而不是Objective-C。以適當的語言發佈答案。 – rmaddy

+0

這種工作方式也是如此,只是試圖使3種顏色如上所述工作,現在擺弄indexPath。 –

相關問題