作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在屏幕上有 3 个 UiLabel。我有一个带有颜色的数组,例如红色,绿色,蓝色。我想将每个 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(), "红色"), (UIColor.greenColor(), "绿色"), (UIColor.blueColor(), "蓝色")]
//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)
最佳答案
您可以存储包含实际 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())
关于ios - 从数组中选择 UIlabel 背景颜色,然后将其从数组中删除。 ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528793/
我是一名优秀的程序员,十分优秀!