屏幕上有3个UiLabels。我有一个颜色的数组,例如红,绿,蓝。我想将每个UiLabel的背景设置为数组中的颜色,然后从数组中删除颜色,这样就没有2个UiLabel具有相同的颜色。
我试图做这样的事情。它在数组中选择一个随机字符串但是我不能将它分配给uilabel,因为它不是UIColor类型。
override func viewDidLoad() {
super.viewDidLoad()
let Colorarray = ["UIColor.redColor()", "UIColor.greenColor()", "UIColor.blueColor()"]
let randomIndex = Int(arc4random_uniform(UInt32(Colorarray.count)))
print(randomIndex)
self.left.text = (Colorarray[randomIndex])
self.left.backgroundColor = (Colorarray[randomIndex])
self.middle.backgroundColor = (Colorarray[randomIndex])
self.right.backgroundColor = (Colorarray[randomIndex])
}
这是我试过的第二个代码
var colorArray = [(UIColor.redColor(),“Red”),(UIColor.greenColor(),“Green”),(UIColor.blueColor(),“Blue”)]
//random color
let randomIndex = Int(arc4random_uniform(UInt32(colorArray.count)))
//accessing color
var (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
let leftColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(leftColorRemoval)
var (mcolor, mname) = colorArray[randomIndex]
self.middle.text = mname
self.middle.backgroundColor = mcolor
let middleColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(middleColorRemoval)
var (rcolor, rname) = colorArray[randomIndex]
self.right.text = rname
self.right.backgroundColor = rcolor
let rightColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(rightColorRemoval)
答案 0 :(得分:1)
您可以存储包含实际UIColor
和字符串值的元组数组。这使得您可以提供所需的任何字符串值:
let colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]
然后,访问随机颜色:
let (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
...
在我看来,您的代码实际上并没有删除随机颜色。以下是您实际操作的方式(多种方式之一):
let random = { () -> Int in
return Int(arc4random_uniform(UInt32(colorArray.count)))
} // makes random number, you can make it more reusable
let (leftColor, leftName) = colorArray.removeAtIndex(random()) // removeAtIndex: returns the removed tuple
let (middleColor, middleName) = colorArray.removeAtIndex(random())
let (rightColor, rightName) = colorArray.removeAtIndex(random())