gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:26:54 30 4
gpt4 key购买 nike

我有一个创建 CGRect 的函数,我正在尝试为它们中的每一个分配随机颜色。

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

Cannot call value of non-function type "[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
}

如果有人能解决这个问题那就太棒了。任何帮助将不胜感激!提前致谢。

最佳答案

这个:

newBox.backgroundColor = UIColor(colors(randomNum))

应该是:

newBox.backgroundColor = colors[randomNum]

colors 是一个 UIColor 数组。您只需要数组中的一个元素。

你还应该改变:

let randomNum:UInt32 = arc4random_uniform(4)

到:

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

这样如果你向数组中添加更多的颜色,你不需要调整这条线。它使您的代码不易出错。

关于ios - 对应于 UIColors 数组的随机数 - ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43146367/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com