IBOutlet is nil, but it is connected in storyboard

2020-01-23 16:50发布

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.

30条回答
相关推荐>>
2楼-- · 2020-01-23 17:34

This was happening to me with my custom collection view cell. Turns out I had to replace my registerClassforReuseIdentifier method with registerNib. That fixed it for me.

查看更多
不美不萌又怎样
3楼-- · 2020-01-23 17:34

You can validate if the is view is loaded.

if isViewLoaded && view.window != nil {
 //self.annotationOptionsView.
}
查看更多
地球回转人心会变
4楼-- · 2020-01-23 17:35

I had the same problem after copying a class (linked to a xib) to reuse it with another viewcontroller class (linked to a storyboard). I forgot to remove

override var nibName

and

override var nibBundle

methods.

After removing them, my outlets started to work.

查看更多
【Aperson】
5楼-- · 2020-01-23 17:36

Other case:

Your outlets won't get set until the view controller's view is actually instantiated, which in your case is probably happening shortly after initWithNibName:bundle:—at which point they'll still be nil. Any setup you do that involves those outlets should be happening in your view controller's -viewDidLoad method.

查看更多
戒情不戒烟
6楼-- · 2020-01-23 17:37

For Swift 3.

func configureView() {
    let _  = self.view
}
查看更多
疯言疯语
7楼-- · 2020-01-23 17:37

Yet another case I just ran into. I changed the name of my class for the UIViewController, but I forgot to change the name of the .xib file where the interface was built.

Once I caught this and made the file names reflect the class name, it was all good!

I hope that helps someone.

查看更多
登录 后发表回答