gpt4 book ai didi

ios - 从数组中选择 UIlabel 背景颜色,然后将其从数组中删除。 ( swift )

转载 作者:行者123 更新时间:2023-11-29 01:13:05 27 4
gpt4 key购买 nike

我在屏幕上有 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/

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