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.

Image for post
Image for post

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:

Image for post
Image for post
star rating view

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

Image for post
Image for post
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.

Image for post
Image for post

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.

Image for post
Image for post
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 Medium for fresh articles. Also, connect with me on LinkedIn.

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

Written by

iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store