2017-03-31 53 views
0

我有一個函數可以創建一個CGRect,我試圖給它們分配一個隨機顏色。與UIColors數組對應的隨機數ERROR

我創建顏色作爲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 
} 

如果任何人都可以解決這將是驚人的。任何幫助將非常感謝!預先感謝一噸。

+1

'colors [int(randomNum)]' –

回答

2

此:

newBox.backgroundColor = UIColor(colors(randomNum)) 

應該是:

newBox.backgroundColor = colors[randomNum] 

colorsUIColor陣列。你只需要數組中的一個元素。

你也應該改變:

let randomNum:UInt32 = arc4random_uniform(4) 

到:

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

如果你添加更多的色彩到數組這樣,就不需要調整這一行。它使你的代碼更容易出錯。

+0

嘿!非常感謝!!它看起來像會工作,但我得到一個錯誤:不能用類型'UInt32'的索引下標''[UIColor]'類型的值。你知道這是爲什麼嗎? –

+0

查看我的更新。你需要把'arc4random_uniform'的結果作爲'Int'。 – rmaddy

+0

完美!非常感謝。 –