Reputation: 241
So, I have 20 UI buttons on a single viewcontroller. I also have 2 other buttons there that will change the currentTitle or background color of different groups of those buttons. (for example, pressing one of those 2 buttons will change the color of 10 other buttons, while pressing the other button will change the background of 15 of those buttons.)
Am I doomed to having to create 20 different IBOutlets like:
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
.
.
.
and then having to write an additional 25 lines of:
button1!.setTitleColor(UIColor.redColor(), forState: .Normal()
button2!.setTitleColor(UIColor.redColor(), forState: .Normal()
button3!.setTitleColor(UIColor.redColor(), forState: .Normal()
Surely theres an easier way to do this? I can't link more than one UI with IBOutlet, and changing the tags for the buttons don't do much either because I still have to write the darn things down 25 times regardless.
Is it possible to put those buttons into groups where I can write a single line of code to change ALL things in that group?
Upvotes: 3
Views: 1255
Reputation: 152
Set your button tags in series like 101 to 125 and on click of any button perform this operation
for(UIButton *button in <parent view of buttons>.subviews){
if(button.tag >= 101 && button.tag <= 125){
button.setTitleColor(UIColor.redColor(), forState: .Normal()
}
}
For Swift
for subview in self.createBugView.subviews {
if let button = subview as? UIButton {
// this is a button
if(button.tag >= 101 && button.tag <= 125){
button.setTitleColor(UIColor.red, for: .normal)
}
}
}
Upvotes: 3