What is an IBOutletCollection in iOS??

When we try to create a new IBOutlet or new IBAction, a third option shows up named IBOutletCollection. I always wondered what it is, but never got a chance to check that out. If you already know what it is, then please skip this article.

Abhimuralidharan
Aug 23, 2017 · 3 min read

As the name says, an IBOutletCollection is a collection of IBOutlets. It can either be a collection of UI elements.

An IBOutletCollection of UIButton in code will look like this:

@IBOutlet var starButtons: [UIButton]!

It will be an array of UIButton objects.

There are two rather curious things to note about an IBOutletCollection array:

  • Its order is not necessarily guaranteed. The order of an outlet collection appears to be roughly the order in which their connections are established in Interface Builder. However, there are numerous reports of that order changing across versions of Xcode, or as a natural consequence of version control. Nonetheless, having code rely on a fixed order is strongly discouraged.
  • No matter what type is declared for the property, an IBOutletCollection is always an NSArray

The next time you’re managing a significant or variable number of outlets in an iOS view, take a look at IBOutletCollection.

Example:

Let’s create a star rating view as in the UI shown below:

star rating view

For this, let’s create a horizontal stackview with five buttons as shown below.

storyboard implementation

Now control + drag the first star to the ViewController and create an IBOutletCollection named starButtons.

@IBOutlet var starButtons: [UIButton]!

Now link all other buttons one by one by clicking and dragging the small circle near the IBOutletCollection to the button.

Set tag to all the buttons in the correct order . ie; from 1 to 5.

Connect all the buttons to a common IBAction for event touchupInside .

@IBAction func buttonTapped(_ sender: UIButton) {print(“Rated \(sender.tag) stars.”)for button in starButtons {if button.tag <= sender.tag {button.setImage(UIImage.init(named: “star_selected”), for: .normal)} else {button.setImage(UIImage.init(named: “star_normal”), for: .normal)}}}

Boom!! Compile and run the app.

working gif

Watch the following video to understand more :

Enjoy!!

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

You can follow me on for fresh articles. Also, connect with me on .

If you have any comment, question, or recommendation, feel free to post them in the comment section below!

)

Abhimuralidharan

Written by

iOS and tvOS developer, dreamer, photographer 🤨

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade