Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect all UI Elements to one outlet at once, swift [duplicate]

Tags:

xcode

ios

Using Swift 2 and XCode 7.2.1, is there a way to connect all of the UI Elements (buttons and labels) to one outlet? I feel like this would be done by doing CMD-A on all your elements then control-dragging to your code, but this only hooks up one of the selected elements to the outlet.

like image 777
owlswipe Avatar asked Mar 18 '16 18:03

owlswipe


1 Answers

You can not do this.

The only things that multiple UI elements can be hooked up to are actions or outlet collections.

Importantly, an outlet is a single reference to a single object:

@IBOutlet weak var label: UILabel!

Just like with any other variable, it can't be two or more things at once. It can only be one thing. If I hook another thing up to this outlet, it will unhook whatever was previously hooked up to it.


However, I can make an outlet collection:

enter image description here

@IBOutlet strong var labels: [UILabel]!

I don't believe there is a short-cut to hooking up multiple elements at once, but you can hook up multiple elements (albeit it one at a time).


It's important to note that by default, Xcode will create the outlet collection as the exact type of whatever you dragged in, and you'll only be able to add elements of that type or subclasses of that type to the collection.

You can, however, manually change the type to a broader type and thereby hook up a wider variety of things:

@IBOutlet strong var labels: [UIView]!

enter image description here

enter image description here


Likewise, multiple objects of varying types can be hooked up to an @IBAction as long as the interface for the method makes sense:

@IBAction func action(sender: AnyObject) {
    // write code to handle action here
}

enter image description here

like image 80
nhgrif Avatar answered Nov 12 '22 12:11

nhgrif