【问题标题】:generate a random background color for each item in forEach loop为 forEach 循环中的每个项目生成随机背景颜色
【发布时间】:2021-05-25 04:42:36
【问题描述】:

我想做的是看看是否有可能在 for each 循环中我可以为每个项目分配随机背景颜色。我尝试了下面的一些方法,但无法编译。我知道有一种方法可以通过在 for each 之外设置一个变量并作为 uicolor 的一部分增加,但我想看看是否有一种方法可以在不创建变量的情况下做到这一点。

   var frontBox = UIButton()
var backBox = UIButton()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    [frontBox,backBox,slider].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.backgroundColor = ar4random().uicolor
    }
    

}

【问题讨论】:

    标签: swift foreach arc4random


    【解决方案1】:

    Swift 不再使用 ar4random - 要获取随机数,您使用 .random(in: 0...1) or similar

    另外,$0.backgroundColor 接受 UIColor,而不是数字。您可能正在寻找这样的东西:

    $0.backgroundColor = UIColor(
        red: .random(in: 0...1),
        green: .random(in: 0...1),
        blue: .random(in: 0...1),
        alpha: 1
    )
    

    这组成了一个UIColor from red, green, and blue components,每个都是一个从01的随机数。

    【讨论】:

      【解决方案2】:

      这取决于您希望这些颜色有多“随机”。如果你想要噪音,请按照 aheze 的建议。

      如果你想要一些视觉上吸引人的东西,比如演示一个新的布局,试试这样:

      import UIKit
      
      let stackView = UIStackView(frame: CGRect(x: 0,y: 0,width: 600,height: 100))
      stackView.distribution = .fillEqually
      let collection = 1...100
      collection.forEach { i in
          let view = UIView()
          let hue = CGFloat(i) / CGFloat(collection.count)
          view.backgroundColor = UIColor.init(hue: hue, saturation: 1, brightness: 1, alpha: 1)
          stackView.addArrangedSubview(view)
      }
      
      

      关键是在 UIColor 上使用init(hue:saturation:brightness:alpha:) API 并控制hue 参数来改变颜色。
      该示例应该为您提供特定用例所需的一切。

      操场截图:

      【讨论】:

        猜你喜欢
        • 2019-05-09
        • 1970-01-01
        • 2013-10-14
        • 2012-07-12
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 2011-09-08
        • 2014-02-12
        相关资源
        最近更新 更多