我将如何以编程方式更改单元格的背景颜色

时间:2015-10-07 03:47:21

标签: ios swift uitableview uicolor

所以我的实际问题更加强大。我很好奇是否可以通过编程方式更改单元格的背景颜色,但这可能是基于单元格是第一个还是第二个等等。

我不确定这是否可行,但我想要实现的是利用细胞增加数量的梯度效应。

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

我尝试过这样的事情,至少让颜色交替出现,看看我能否弄清楚接下来要做什么,但这已经失败了。交替似乎不是正确的选择,但它可能是开始编程我想要发生的正确方法。

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

是的,可以根据单元格是第一个还是第二个等以编程方式更改单元格的背景颜色。在cellForRowAtIndexPath委托方法中,检查行是否为奇数然后放置不同的背景颜色,如果它甚至然后把不同的颜色。通过使用下面的代码,您将获得行的替代颜色。

- (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
}

答案 2 :(得分:0)

Swift 4.2

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if indexPath.row % 2 == 0 {

         cell.backgroundColor = UIColor.red
         //OR
         productCell.contentView.backgroundColor = UIColor.red
    }
    else {

         cell.backgroundColor = UIColor.blue
    }

    return cell
}
相关问题