0

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 ?

Annie
  • 51
  • 7
  • possible duplicate of [How can I use IBOutletCollection to connect multiple UIImageViews to the same outlet?](http://stackoverflow.com/questions/15836930/how-can-i-use-iboutletcollection-to-connect-multiple-uiimageviews-to-the-same-ou) – Kevin May 22 '15 at 03:03

3 Answers3

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