generate a random background color for each item in forEach loop

237 Views Asked by At

What I would like to do is see if its possible when in a for each loop that i can a assign a random background color to each item.I tried something below but that does not compile. I know there is a way to do this by setting a variable outside the for each and increasing as part of a uicolor but I want to see if there is a way to do this without creating a variable.

   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
    }
    

}
2

There are 2 best solutions below

0
aheze On BEST ANSWER

Swift doesn't use ar4random anymore - to get a random number, you use .random(in: 0...1) or similar.

Also, $0.backgroundColor takes in a UIColor, not a number. You are probably looking for something like this:

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

This composes a UIColor from red, green, and blue components, which are each a random number from 0 to 1.

0
de. On

It depends on how "random" you want these colors to be. If you want noise, go with aheze's suggestion.

If you want something visually appealing, say, to demo a new layout, try something like this:

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)
}

The key is using the init(hue:saturation:brightness:alpha:) API on UIColor and control the hue parameter to change the color.
The example should give you all you need for your specific use case.

Screenshot from the playground:

visualization