Search code examples
swiftinterface-builderiboutletiboutletcollection

Swift - IBOutletCollection equivalent


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.


Solution

  • EDIT

    This was fixed in a later Beta release of Swift - there's now in IBCollection option in the interface builder.


    For early Beta releases of Swift:

    I came across the same problem: in the release notes of Beta 2 you find the following statement:

    Interface Builder does not support declaring outlet collections in Swift classes

    I solved this the following way (easy to customize):

    class CardGameViewController: UIViewController {
      @lazy var cardButtons : UIButton[] = {
        var tempBtn: UIButton[] = []
        for v:AnyObject in self.view.subviews {
          if v is UIButton {
            tempBtn.append(v as UIButton)
          }
        }
        return tempBtn
      }()
    ...
    

    Basically, it loops through all the subviews and checks if one is a UIButton. In that case it gets added to a temporary array. This temporary array is then used to lazy instantiate the cardButtons array. For all details, check: Matchismo: Objective-C to Swift