What is an IBOutletCollection in iOS??

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 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!

--

--

--

iOS and tvOS developer, dreamer, photographer 🤨

Love podcasts or audiobooks? Learn on the go with our new app.

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
Abhimuralidharan

Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨

More from Medium

iOS UISwitches — Touch Behaviour Notes.

Choosing properties to Encode and Decode using CodingKeys

Every iOS developer should know these Xcode tricks

The blogs while was worked True Digital Academy