How to change every background color of uitableviewcell

I want to change the background color of each cell in order.

These are my colors. And I just want to show them as shown in the image.

I show 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

+4
source share
2 answers

You need to delete this line

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

from your function willDisplayCell, because it already has your cell in the parameters, and you just override it with a new cell, and your new cell will never be used.

If you want to show the colors in order, 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])
}
+6
source

, , , .

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

cellForRowAtIndexPath . , - .

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

Source: https://habr.com/ru/post/1650637/


All Articles