2015-10-07 177 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。 –

相关问题