我正在制作此应用程序,假设我得到了rgba颜色的红色,绿色和蓝色的CGFloat值。我使用它们为tableView中的单元格赋予颜色。有些效果很好,但有些是黑色,而不是应有的颜色。尽管主要是深色,但我对此深有怀疑。我不知道为什么会这样。
代码如下:
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
}
一些例子:
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]
浅绿色,浅蓝色和黄色。深绿色,深蓝色和紫色没有。
答案 0 :(得分:2)
76/255
,153/255
,102/255
和204/255
是整数除法,并且全部等于0
。
要解决此问题,只需添加.0
,使分子或分母加倍:
76/255.0
,76.0/255.0
或76.0/255.0
您还应该确保所有其他颜色也是真实划分。
答案 1 :(得分:1)
这是因为将两个Int
相除会导致另一个Int
,而您需要一个Double
。将它们转换为CGFloat
,因为UIColor
初始化程序始终接受CGFloat
。还将colorArray
定义为[CGFloat]
。
case "Light green":
colorArray = [CGFloat(128)/CGFloat(255), 1, 0]
case "Dark green":
colorArray = [CGFloat(76)/CGFloat(255), CGFloat(153)/CGFloat(255), 0]
case "Light blue":
colorArray = [0, 1, 1]
case "Dark blue":
colorArray = [CGFloat(51)/CGFloat(255), CGFloat(51)/CGFloat(255), 1]
case "Purple":
colorArray = [CGFloat(102)/CGFloat(255), 0, CGFloat(204)/CGFloat(255)]
case "Yellow":
colorArray = [1, 1, 0]
答案 2 :(得分:0)
正如其他答案所暗示的那样,Swift类型推断不知道这些数组应该具有类型CGFloat
。例如,如果您使用let foo: CGFloat = 123/255
,那将不是整数除法。但是,这些数组组件的类型仍推断为Int
。因此,您变得黑了,因为任何小于1的除法都会被限制为0。
如果出于某种原因必须使用在问题中定义的设置,则可以使用元组代替数组:
typealias ColorTuple = (red: CGFloat, green: CGFloat, blue: CGFloat)
// ...
var colorTuple: ColorTuple?
let myColor = "Light green" // for example
switch myColor {
case "Light green":
colorTuple = (128/255, 1, 0)
case "Dark green":
colorTuple = (76/255, 153/255, 0)
case "Light blue":
colorTuple = (0, 1, 1)
case "Dark blue":
colorTuple = (51/255, 51/255, 1)
case "Purple":
colorTuple = (102/255, 0, 204/255)
case "Yellow":
colorTuple = (1, 1, 0)
default:
break
}
与其他建议相比,这样做的好处是简洁得多。如果需要将其用作数组,则可以在以后创建适当的数组。
无需多说就很难说,但是您可能会发现在UIColor
上使用扩展名为静态lightGreen
,darkGreen
等的静态变量,这些变量返回使用初始化的UIColor
实例RGB初始化器将比您这里拥有的更好。