对应于UIColors-ERROR数组的随机数

时间:2017-03-31 17:20:33

标签: ios swift uikit uicolor

我有一个创建CGRect的函数,我试图为每个函数分配一个随机颜色。

我将颜色创建为类型为UIColor的变量,然后将它们放入名为colors的数组中。然后,我创建了一个随机数生成器,并在定义CGRect的背景颜色时调用它,但我收到错误:

  

无法调用非功能类型的值" [UIColor}"

这是为什么?这是我的代码:

func addBox(location: CGRect) -> UIView {
    let newBox = UIView(frame: location)

    let red = UIColor(red: (242.0/255.0), green: (186.0/255.0), blue: (201.0/255.0), alpha: 1.0)
    let green = UIColor(red: (186.0/255.0), green: (242.0/255.0), blue: (216.0/255.0), alpha: 1.0)
    let yellow = UIColor(red: (242.0/255.0), green: (226.0/255.0), blue: (186.0/255.0), alpha: 1.0)
    let blue = UIColor(red: (186.0/255.0), green: (216.0/255.0), blue: (242.0/255.0), alpha: 1.0)
    let colors = [red, green, yellow, blue]
    let randomNum:UInt32 = arc4random_uniform(4)

    newBox.backgroundColor = UIColor(colors(randomNum))

    hView.insertSubview(newBox, at: 0)
    return newBox
}

如果有人能解决这个问题,那就太棒了。任何帮助都会非常感激!!非常感谢。

1 个答案:

答案 0 :(得分:2)

此:

newBox.backgroundColor = UIColor(colors(randomNum))

应该是:

newBox.backgroundColor = colors[randomNum]

colorsUIColor的数组。你只需要数组中的一个元素。

您还应该更改:

let randomNum:UInt32 = arc4random_uniform(4)

为:

let randomNum = Int(arc4random_uniform(colors.count))

这样,如果向阵列添加更多颜色,则无需调整此行。它使您的代码不易出错。