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?
Asked
Active
Viewed 712 times
2 Answers
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
-
Thanks Moe, i'will try this and tell you back if it's working. – Wills Dec 10 '17 at 17:03
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
-
-
Thanks again for your help. I don't use this solution, but it inspire me for find mine. Thanks again – Wills Dec 15 '17 at 21:37