swiftxcodeinterface-builderxibloadnibnamed

Strong IBOutlet nil in XIB with multiple views


Calling Bundle.main.loadNibNamed to load a .xib file which contains (n) multiple variants of one UI defined with multiple UIViews instantiates n instances of my subclass.

I then apply a filter expression to choose the correct variant with .first(where: { $0.restorationIdentifier == <correct restoration ID>.

In this instance my filter expression correctly returns the 5th UIView inside of my .xib but the @IBOutlets in my custom class are connected to the 1st UIView that was instantiated but which is immediately deprecated by what I assume is ARC.

This leads me to having unexpectedly nil IBOutlets. What can be done to connect the IBOutlets to the correct (5th in this case) UIView returned by Bundle.main.loadNibBaned


Solution

  • The problem is that loadNibNamed is instantiating all your views, and you're only choosing to keep some of them around. In the process, IB outlets are assigned in some order, which most likely doesn't end up with your desired object being assigned to an outlet last.

    I don't think a nib file gives you a way to instantiate only some of its multiple top level objects. You need to either split your various views into multiple nibs (and only load the one you need), or switch to using a Storyboard, which does let you instantiate specific objects by their identifier.