0

I'm trying to load a ViewController (a custom UIViewController subclass) from an .xib in Swift via the storyboard (I created a ViewController instance in the storyboard and deleted its view).

The ViewController itself loads, but nothing in the .xib loads with it.

In other words, my .xib looks like this:

enter image description here

ShapeView is a custom UIView subclass.

But if I look at the view which is actually loaded:

override func awakeFromNib() {
    log.info("view \(self.view)")
}

self.view is just a generic UIView -- it's not my ShapeView.

If I try creating an @IBOutlet and connecting my ShapeView to it, the same thing happens -- the property bound to the outlet is nil:

enter image description here

If I use Obj-C for my ViewController class keeping everything else the same (the .xib and storyboard), it works as expected.

How do I set up and/or load the .xib in Swift via the storyboard to get the correct behavior?

Anna Dickinson
  • 3,217
  • 21
  • 42
  • It's not clear how you're loading your xib based view. You created a controller in the storyboard, and deleted its view, but then how are you trying to get the xib view to be the controller's view? Do you have any code in the controller that loads the xib? – rdelmar Nov 09 '14 at 16:17
  • In the storyboard, if you create a view controller of some class and then delete its view, it looks for an .xib with the same name as the class and loads it at runtime. (It's a standard "trick"). That's how I'm loading the .xib -- I'm not explicitly loading it in the class init method. If I do the exact same thing in Obj-C, it works! – Anna Dickinson Nov 09 '14 at 16:24
  • It looks like this trick doesn't work in Swift, so you'll have to load the xib manually. Are you asking how to do that, or if there's a way to get the "trick" to work with Swift? – rdelmar Nov 09 '14 at 16:46
  • How to get the trick to work. I like that trick because it doesn't require coding an init method to explicitly load the nib. Just seems cleaner. Is there a better way to do something similar in Swift? – Anna Dickinson Nov 09 '14 at 17:01
  • I don't know why the trick doesn't work in Swift, so I don't know a better way. I'm not a big fan of the "trick", because it makes your code less self-documenting. The same with using alloc init to instantiate a view controller with an eponymous xib -- it makes your code a little shorter at the expense of clearly showing your intent. – rdelmar Nov 09 '14 at 17:13
  • This shows how to load a custom view from a xib file (though not a view controller) http://stackoverflow.com/a/34524346/3681880 – Suragch Dec 30 '15 at 07:06

0 Answers0