Can I connect multiple objects with different tags to the same IBOutlet?
Asked Answered
J

2

8

I have 30 buttons in one view in Interface Builder. Each has a different tag between 100001 and 100030. I've found it easy to use the same action for each button, passing along the tag for each one when pressed and using code to decide which level to load.

I want to connect all the buttons to a single IBOutlet, but have each button load a different image based on the user's saved data and the button's tag.

How do I do this?

Judicious answered 19/12, 2011 at 16:23 Comment(0)
S
25

Use IBOutletCollection to add an outlet collection to your view controller, like this:

@property (retain, nonatomic) IBOutletCollection(UIButton) NSMutableSet* buttons;

This will let you connect all your buttons to one outlet. The property buttons will be a NSMutableSet containing all your buttons. You can continue to identify individual buttons using the button's tag property. This is handy if you want to iterate through all your buttons, perhaps to set up each button's image:

for (UIButton *b in self.buttons) {
    b.imageView.image = [self imageForTag:b.tag];
}

(You'll need to supply the -imageForTag: method to provide the right image for a given tag, or find some other way to map from tags to images.)

Of course, if you already know the range of tag values for all your buttons, and if you've taken care to make the tags unique inside the view containing all the buttons, you can also just fetch each button individually using -viewWithTag:. This is probably not as fast as having the whole set of buttons already created, as you have with the outlet collection described above, but it does mean that there's one less thing to maintain.

Samphire answered 19/12, 2011 at 16:39 Comment(2)
Yes, spot on! Ive just tried this, and NSLog'ed the count of the array, and its connecting the button perfectly... The only this I dont know how to do is then use this to change this buttons image? What do I do code wise? Thanks!Judicious
Setting the button's image is no different using the IBOutletCollection than it is using a plain old IBOutlet, except that you first have to get each button from the collection. I added a little snippet above that may help.Samphire
D
1

Follow these steps to create an array of outlets an connect it with IB Elements:

  • Create an array of IBOutlets
  • Add multiple UIElements (Views) in your Storyboard ViewController interface
  • Select ViewController (In storyboard) and open connection inspector
  • There is option 'Outlet Collections' in connection inspector (You will see an array of outlets there)
  • Connect if with your interface elements

-

class ViewController2: UIViewController {


    @IBOutlet var collection:[UIView]!


    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

enter image description here

Docila answered 18/10, 2017 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.