Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 495
James Chen Avatar asked Jan 18 '26 03:01

James Chen


1 Answers

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
}
like image 88
Mayank Patel Avatar answered Jan 19 '26 17:01

Mayank Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!