Swift - IBOutletCollection equivalent

Alcanzar picture Alcanzar · Jun 5, 2014 · Viewed 32.8k times · Source

I'm trying to replicate the Stanford Matchismo game from "Developing ios7 apps for iphone and ipad" in iTunesU in Swift.

On page 77 of the 3rd lecture slides, it shows using an IBOutletCollection which isn't an option on Swift. The Swift doc example shows one example that has an array of IBOutlet, but I can't figure out how to make Interface Builder connect multiple outlets to the same IBOutlet/IBOutlet Array.

Has anyone figured out how to do this yet?

I know that I can create 12 outlets and deal with it that way, but I'd like to make this work as closely as possible to the example in the lecture slides.

Answer

Nate Cook picture Nate Cook · Jun 5, 2014

Update: This works properly in Xcode now - "Outlet Collection" is one of the connection options in Interface Builder, which creates something that looks like:

@IBOutlet var labelCollection: [UILabel]!

While we're waiting for a fix, you can approximate this using a computed property. Let's say my view has five UILabels that I want in a collection. I still have to declare each one, but then I also declare a computed property that collects them:

class MyViewController {
    @IBOutlet var label1 : UILabel
    @IBOutlet var label2 : UILabel
    @IBOutlet var label3 : UILabel
    @IBOutlet var label4 : UILabel
    @IBOutlet var label5 : UILabel
    var labels: UILabel![] { return [label1, label2, label3, label4, label5] }

Kind of annoying, but from then on we can treat the labels property as if it were an IBOutletCollection, and won't have to change the rest of our code once the bug is fixed:

override func viewDidLoad() {
    super.viewDidLoad()

    for (index, item) in enumerate(self.labels) {
        item.text = "Label #\(index)"
    }
}