在XCode中随机化颜色

时间:2015-07-26 04:04:48

标签: ios xcode swift colors uicolor

我试图用我已经创建的一些颜色随机化XCode中标签的文本颜色,我尝试了不同的方法,这是我得到的最接近的。

    override func viewDidLoad() {
    super.viewDidLoad()

    let color1 = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
    let color2 = UIColor(red: 80/255, green: 1, blue: 200/255, alpha: 1)
    let color3 = UIColor(red: 150/255, green: 80/255, blue: 1, alpha: 1)
    let color4 = UIColor(red: 1, green: 80/255, blue: 80/255, alpha: 1)
    let color5 = UIColor(red: 80/255, green: 1, blue: 80/255, alpha: 1)

    var randomEight = arc4random_uniform(5)+1
    var randomColor:String = String(format:"color%i", randomEight)

    randomLabel.textColor = randomColor
}

但是, randomColor 变量是一个字符串,我无法将其转换为UIColor。

4 个答案:

答案 0 :(得分:2)

将所有颜色放在数组中,然后使用randomEight作为数组中的索引以获得正确的颜色。此外,您可能需要检查整数除法以确保获得正确的颜色。

let color1 = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
let color2 = UIColor(red: 80/255, green: 1, blue: 200/255, alpha: 1)
let color3 = UIColor(red: 150/255, green: 80/255, blue: 1, alpha: 1)
let color4 = UIColor(red: 1, green: 80/255, blue: 80/255, alpha: 1)
let color5 = UIColor(red: 80/255, green: 1, blue: 80/255, alpha: 1)

let colors = [color1, color2, color3, color4, color5]
let randomEight = Int(arc4random_uniform(UInt32(colors.count)))

randomLabel.textColor = colors[randomEight]

答案 1 :(得分:1)

将颜色放入数组中,然后选择随机索引,例如:

let colors: [UIColor] = [ UIColor.redColor(),
                          UIColor.blueColor(),
                          UIColor.greenColor()
                        ] // ^- replace with your own colors

let randomColor = colors[Int(arc4random_uniform(UInt32(colors.count)))]

请注意与arc4random_uniform一起使用的必要演员表。另请注意,索引从0开始,因此请勿将1添加到随机数。

不需要randomEight(无论如何为什么是“8”?),如果单一文字颜色是你使用颜色的唯一地方,你甚至可以省略{{1}并直接分配给randomColor

答案 2 :(得分:0)

var framejQuery = $('#frameID')[0].contentWindow.$;
var element = $('#frameID').contents().find('#gridID')[0];
var grid = framejQuery.data(element, 'kendoGrid');         // Here's your grid object

答案 3 :(得分:0)

试试这个oneliner;)

 randomLabel.textColor = UIColor(red : CGFloat(arc4random_uniform(255)) , green : CGFloat(arc4random_uniform(255)), blue : CGFloat(arc4random_uniform(255)) , alpha : 1)