Murat Kaya
Murat Kaya

Reputation: 1321

How to change each uitableviewcell background color

I want to change each cell background color in order.

This is my colors.And I just want to show them as shown in image.

I'm showing it with random colors now.But I want to show them in order.

var cellColors = ["F28044","F0A761","FEC362","F0BB4C","E3CB92","FEA375"]
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! GroupTableViewCell
        let randomColor = Int(arc4random_uniform(UInt32(self.cellColors.count)))
        cell.contentView.backgroundColor = UIColor(hexString: self.cellColors[randomColor])
    }

enter image description here

Upvotes: 8

Views: 17538

Answers (2)

Yury
Yury

Reputation: 6114

You need to delete this line

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! GroupTableViewCell

from your willDisplayCell function, because it already have your cell in parameters, and you just overriding it with new cell, and your new cell will be never used.

If you want to show colors in order, then you can use indexPath:

var cellColors = ["F28044","F0A761","FEC362","F0BB4C","E3CB92","FEA375"]
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.contentView.backgroundColor = UIColor(hexString: cellColors[indexPath.row % cellColors.count])
}

Upvotes: 9

Yannick
Yannick

Reputation: 3278

Make an array with the colors, maybe you have to create them dynammically but in this example they are hardcoded.

let bgColors = [UIColor.blackColor(), UIColor.grayColor(), UIColor.whiteColor()];

Then in your cellForRowAtIndexPath take the color at the correct index and set it for the cell. I don't know your actual setup but something similar to this should work.

let bgColor = bgColors[indexPath.row]
cell.contentView.backgroundColor = bgColor

Upvotes: 3

Related Questions