-1

I would like to apply different color (by the code) at different uiButton. I thinked to create 2 arrays. The first with my uiButtons, and the other with differents colors. After that, to make a first loop with my buttons, and inside this loop, to make an other loop with the colors (random result). The last step, apply the colors at the button. Can this way work?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Wills
  • 31
  • 5

2 Answers2

0

You can do that by making use of this answer.

let numberOfButton = 10
var buttons = [UIButton]()

for _ in 0..<numberOfButton {
    let button = UIButton()
    button.setTitleColor(.random(), for: .normal)
    buttons.append(button)
}
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
0

You can try this.Its working code just call the method from viewDidLoad and see how it works

func createButtonsWithDifferentTitleColor(){
    // create array of different colors
    let colorArray = [UIColor.red,UIColor.green,UIColor.blue,UIColor.brown,UIColor.purple]

    for i in 0...colorArray.count-1 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        //set different title colors for each button
        button.setTitleColor(colorArray[i], for: .normal)
        // set different title for button
        button.setTitle("Button No \(i+1)", for: .normal)
         // add all buttons to main view, so that they can be visible
        view.addSubview(button)

    }

}

For setting random color you ned to do some thing like this

 func createButtonsWithDifferentTitleColor(){
    // create array of different colors
    let colorArray = [UIColor.red,UIColor.green,UIColor.blue,UIColor.brown,UIColor.purple]

    for i in 0...colorArray.count-1 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        // generate random index
        let index = Int(arc4random_uniform(UInt32(colorArray.count)));
        //set different title color for each button
        button.setTitleColor(colorArray[index], for: .normal)
        // set different title for button
        button.setTitle("Button No \(i+1)", for: .normal)
         // add all buttons to main view, so that they can be visible
        view.addSubview(button)

    }

}
Vikky
  • 914
  • 1
  • 6
  • 16