【问题标题】:How to randomly color a UILabel [duplicate]如何为 UILabel 随机着色 [重复]
【发布时间】:2016-05-13 11:26:49
【问题描述】:

我在 CustomCell 中有一个 UILabel,我想在每次将它添加到表格视图时用不同的颜色绘制这个标签。

let myBlue = UIColor(red: 62.0/255, green: 174.0/255, blue: 206.0/255, alpha: 1.0)
let myGreen = UIColor(red: 110.0/255, green: 186.0/255, blue: 64.0/255, alpha: 1.0)
let myRed = UIColor(red: 247.0/255, green: 118.0/255, blue: 113.0/255, alpha: 1.0)
let myYellow = UIColor(red: 255.0/255, green: 190.0/255, blue: 106.0/255, alpha: 1.0)

myLabel.backgroundColor = random(myBlue, myRed, myGreen, myYellow)

有什么建议吗?

谢谢

【问题讨论】:

  • myLabel.backgroundColor = [myBlue, myRed, myGreen, myYellow][Int(arc4random_uniform(4))][myBlue, myRed, myGreen, myYellow][arc4random_uniform(4).hashValue]
  • 如果你想要一个方法func randomColor(colors: UIColor...) -> UIColor { return colors[Int(arc4random_uniform(UInt32(colors.count)))] }
  • 非常感谢您的帮助。

标签: ios swift random


【解决方案1】:
myLabel.backgroundColor = random([myBlue, myRed, myGreen, myYellow])

 func random(colors: [UIColor]) -> UIColor {
         return colors[Int(arc4random_uniform(colors.count))]

 }

【讨论】:

  • 您可以使用可变参数来完全完成 OP 要求的语法
  • 我不得不按照@LeoDabus 的建议将返回值更改为return colors[Int(arc4random_uniform(UInt32(myColors.count)))]。这是我的做法。谢谢let myColors = [myRed, myBlue, myGreen, myYellow]func random(colors: [UIColor]) -> UIColor { return colors[Int(arc4random_uniform(UInt32(myColors.count)))] }myLabel.backgroundColor = random(myColors)
猜你喜欢
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
相关资源
最近更新 更多