I'm making this app and let's say I get the CGFloat values for red, green and blue for an rgba color. I use them to give colors to cells in a tableView. Some work just fine, but some are black instead of the color they should be. It's mainly dark colors, although I highly doubt that has anything to do with it. I don't know why this is happening.
Here's the code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)?.first as! CustomTableViewCell
cell.cellColor.backgroundColor = UIColor(red: CGFloat(myClasses[indexPath.row].red), green: CGFloat(myClasses[indexPath.row].green), blue: CGFloat(myClasses[indexPath.row].blue), alpha: 1.0)
cell.cellLabel.text = myClasses[indexPath.row].name
return cell
}
Some examples:
case "Light green":
colorArray = [128/255, 1, 0]
case "Dark green":
colorArray = [76/255, 153/255, 0]
case "Light blue":
colorArray = [0, 1, 1]
case "Dark blue":
colorArray = [51/255, 51/255, 1]
case "Purple":
colorArray = [102/255, 0, 204/255]
case "Yellow":
colorArray = [1, 1, 0]
Light green, light blue and yellow work. Dark green, dark blue and purple don't.
76/255
, 153/255
, 102/255
and 204/255
is integer division, and all equal 0
.
To solve this just make either the numerator or the denominator double by adding .0
:
76/255.0
, 76.0/255.0
or 76.0/255.0
You should make sure it is real division for all other colors too.