Dave G Dave G - 7 months ago 20
Swift Question

Cannot Set Cell Container BG Programmatically

I have a UITableView cell setup like as BasicCell>ContentView>Container. When I set the container's background in interface builder, I get the desired darker shade of grey that I set it to. However, when I set that darker shade programmatically, in the cellForRowAtIndexPath, I get a white background.

cell.container.backgroundColor = UIColor(red: 20, green: 20, blue: 20, alpha: 1.0)


So by introducing a programmatic color setting, it suddenly ignores both the interface builder color and the programatic color. I've read several threads and tried things like using willDisplay cell:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let myCell = cell as! CustomTableViewCell_F2
myCell.backgroundColor = UIColor.clearColor()
myCell.backgroundView = nil
myCell.container.backgroundColor = UIColor(red: 20, green: 20, blue: 20, alpha: 1.0)
}


I've tried setting it in the CustomTableCell class as well. That didn't work. What's happening and how do I solve it?

Answer

Change

cell.container.backgroundColor = UIColor(red: 20, green: 20, blue: 20, alpha: 1.0)

to

let shade: CGFloat = 0.2
cell.container.backgroundColor = UIColor(white: shade, alpha: 1.0)

Your color UIColor(red: 20, green: 20, blue: 20, alpha: 1.0) is actually white. You should provide values for color components in range 0.0 to 1.0.