Search code examples
iosswiftuitableviewuicolor

How would I programmatically change the background color of a cell


So my actual question is a bit more robust. I'm curious whether it's possible to change the background color of a cell programmatically, however it would be based on whether the cell was first, or second, etc.

I'm not sure this is even possible, but what I'm trying to achieve is a gradient effect utilizing the cells as they increase in number.

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

I've tried something like this to at least have the color alternate to see if I can figure out what to do next, but this has failed. Alternating doesn't seem to be the right option, but it might be the right way to start programming what I want to happen.


Solution

  • A tableView sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. 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
    }