Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBOutlet is nil, but it is connected in storyboard, Swift

Using Swift 1.1 and Xcode 6.2.

I have a UIStoryboard containing a singular, custom UIViewController subclass. On it, I have an @IBOutlet connection of type UIView from that controller to a UIView subclass on the storyboard. I also have similar outlets for subviews of that view. See figure A.

But at run time, these properties are nil (Figure B). Even though I have assured I've connected the outlets in Interface Builder.

Thoughts:

  • Is it possible that because I am using a subclass of a subclass something messes up with the initialization? I am not overriding any initializers
  • awakeFromNib: is not getting called for some reason
  • Maybe it doesn't connecting to subviews on subviews

Things I have tried:

  • Matching @IBOutlet and storyboard item types exactly (instead of UIView)
  • Deleting property and outlet and re-added them

Figure A

Figure A*

Figure B

Figure B

*The obscured code in Figure A is:

@IBOutlet private var annotationOptionsView: UIView!
@IBOutlet private var arrivingLeavingSwitch: UISegmentedControl!

Thank you.

like image 446
Stefan Arambasich Avatar asked Mar 28 '15 19:03

Stefan Arambasich


4 Answers

Typically this happens because your view controller hasn't loaded its view hierarchy yet. A view controller only loads its view hierarchy when something sends it the view message. The system does this when it is time to actually put the view hierarchy on the screen, which happens after things like prepareForSegue:sender: and viewWillAppear: have returned.

Since your VC hasn't loaded its view hierarchy yet, your outlets are still nil.

You could force the VC to load its view hierarchy by saying _ = self.view.

like image 154
rob mayoff Avatar answered Sep 23 '22 05:09

rob mayoff


Did you instantiate your view controller from a Storyboard or NIB, or did you instantiate it directly via an initializer?

If you instantiated your class directly with the initializer, the outlets won't be connected. Interface Builder creates customized instances of your classes and encodes those instances into NIBs and Storyboards for repeated decoding, it doesn't define the classes themselves. If this was your problem, you just need to change the code where you create your controller to instead use the methods on UIStoryboard, or UINib.

like image 36
Jon Hess Avatar answered Sep 23 '22 05:09

Jon Hess


Have you tried running Product > Clean. Solved a very similar problem for me.

like image 31
ThottChief Avatar answered Sep 24 '22 05:09

ThottChief


The storyboard wasn't recognizing any further UI things I added to it. At run time all the references were nil. So I cleared my derived data folder and then those connections worked again.

like image 31
Stefan Arambasich Avatar answered Sep 20 '22 05:09

Stefan Arambasich