3
votes

I want to load a UIView from a XIB file, and I was able to do so successful via:

let nib = UINib(nibName: "CardView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! UIView

Where CardView is the name of my XIB file. Now when I try to add an IBOutlet to the XIB file:

enter image description here

I get this error:

'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key phraseLabel.

I have checked that there aren't any orphan IBOutlets in the XIB file. So thinking that it was because I didn't cast the nib to a CardView class I tried this:

let nib = UINib(nibName: "CardView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! CardView

But I end up with this error:

Could not cast value of type 'UIView' (0x10c058df8) to 'LazyFlashCards.CardView' (0x10934bb00).

So I'm guessing that I'm instantiating the XIB file wrongly but I don't know the "correct" way to do it

2
You need to change the class of the top-level view to your class, not the File's owner - dan
Thanks that fixed it! So the File's Owner is the class that is the "proxy" for the class which loads the file later on, and so the reason that I was getting an error was because my view controller didn't have an IBOutlet called phraseLabel. Is this correct? If so, then what is the purpose of a File's Owner if it is going to replaced by the class that instantiates the NIB anyways? - YellowPillow
"If so, then what is the purpose of a File's Owner if it is going to replaced by the class that instantiates the NIB anyways" Okay, so you don't understand nib-loading? Might help you to read my book: apeth.com/iOSBook/ch07.html#_nib_loading_and_file_8217_s_owner - matt
In addition to @dan 's point: if you've already created the outlets before you change the file's owner and top-level view then you'll need to recreate them after the change. - Paul

2 Answers

0
votes

If you're having issues with this in tests you need to set the owner to your test target.

bundle.loadNibNamed("myNib", owner: testSubject) // owner != nil
-1
votes

I just wrote example to load uiview from XIB by swift, you can read, hope this help you!

https://github.com/lengocgiang/loadViewFromXib