为什么我的背景保持静态黑色



我是快速开发的新手,为了良好的实践,我想尝试让视图的背景颜色完全随机更改。问题是,即使值打印所有随机RGB,颜色也会更改,但仅为黑色。这是我的代码,有人能解释为什么会发生这种情况吗?非常感谢。

@IBAction func changeColor(_ sender: Any) {
let redRGB = CGFloat.random(in: 0...255)
let greenRGB = CGFloat.random(in: 0...255)
let blueRGB = CGFloat.random(in: 0...255)
self.view.backgroundColor = UIColor.init(red: redRGB, green: greenRGB, blue: blueRGB, alpha: 0)
}

您有两个问题:

  1. UIColor.init值从0.01.0,而不是从0.0255.0

  2. 对于不透明,您的alpha需要为10是完全透明的。

    let redRGB = CGFloat.random(in: 0...1)
    let greenRGB = CGFloat.random(in: 0...1)
    let blueRGB = CGFloat.random(in: 0...1)
    self.view.backgroundColor =
    UIColor(red: redRGB, green: greenRGB, blue: blueRGB, alpha: 1)
    

我一直在查看您的代码,发现您正在发送alpha:0。这就是为什么你看到的是黑色的Windows背景色。

以下是正确的代码。

@IBAction func changeColor(_ sender: Any) {
let redRGB = CGFloat.random(in: 0.0...1.0)
let greenRGB = CGFloat.random(in: 0.0...1.0)
let blueRGB = CGFloat.random(in: 0.0...1.0)
self.view.backgroundColor = UIColor.init(red: redRGB, green: greenRGB, blue: blueRGB, alpha: 1)
}

最新更新