【问题标题】:Choose UIlabel background Color from Array and then remove it from array. (swift)从数组中选择 UIlabel 背景颜色,然后将其从数组中删除。 (迅速)
【发布时间】:2016-06-02 09:54:12
【问题描述】:

我在屏幕上有 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(), "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)

【问题讨论】:

    标签: ios swift uilabel uicolor uibackgroundcolor


    【解决方案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())
    

    【讨论】:

    • 感谢您的回复,使用元组似乎可以很好地捐赠颜色。正在玩弄代码,以尝试确保删除先前捐赠的颜色,这样屏幕上就不会出现两次颜色,我想出了这个,但由于某种原因,代码会出现间歇性故障。它只会工作大约四分之一。
    • 见下文我无法在 cmets 中添加它哈哈
    • @PeterGaffney 1. 删除该答案的代码并将其作为编辑添加到您的问题中,这样它就不会被标记。 2.随机性不起作用的原因是它没有每次都获得新的索引。看看我的代码每次如何调用random()
    • 这真是太棒了,它可以与您刚开始的代码一起使用。谢谢人:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2016-07-04
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多