I have a Calculator app. if a user press equal I want to change the background color of all my button(digit 1 to 9) should i have an outlet for each button(each button represent a digit) or there is a way to have one outlet that covers all buttons ?
Asked
Active
Viewed 994 times
3 Answers
7
You want an IBOutletCollection
.
In Objective-C, it would look like this:
@property (nonatomic, strong) IBOutletCollection(UIButton) NSArray* buttons;
In Swift:
@IBOutlet var buttons: [UIButton] = []
Then connect each of your buttons to the buttons outlet in Interface Builder, and you can iterate through each easily.

Dave Wood
- 13,143
- 2
- 59
- 67
2
You can loop all the elements in the UIView and change it programmatically using the code below
for view in self.view.subviews as [UIView] {
if let btn = view as? UIButton {
//do your changes here
btn.backgroundColor = UIColor.redColor()
}
}

Icaro
- 14,585
- 6
- 60
- 75
0
There is a way
control drag each button to the same outlet from the storyBoard. This should hook up each button to one outlet if I am remembering correctly, give it a try and then update your background colors to see if this works.
Of course yes, you can have an outlet for each button if you wish

James Combs
- 324
- 1
- 3
- 15