How to load a UIViewController into live playground via nib?

Hi,

Trying to display a view controller in playground from a nib, but not having much luck. I’ve seen demos where people create a subclass of UIViewController, and inside the “loadView” method, they manually create views. What I’m trying to do is just to setup the viewcontroller (and its views) inside a nib and just load that, and display it in the playground.

So the xib file has a view controller in it, which has a view by default (that’s the result of dragging a view controller object into the xib in IB). The xib file is added to the “Resources” folder inside the playground.

I compile the xib file at the terminal using ibtool --compile MyViewController.nib MyViewController.xib.

I have a swift file added to the playground’s “Sources” folder. The swift file is called the same way as the xib/nib files “MyViewController”.

Inside the swift file is my class definition, which is pretty much nothing but an empty class declaration class MyViewController: UIViewController {}

Then, in the playground file I’m initing my viewcontroller from the nib file:

PlaygroundPage.current.liveView = vc```

This is giving me the error: "loaded the "MyViewController" nib but the view outlet was not set"

I don't know how to set the outlets, since it's not possible to drag and drop or assign outlets to/from a nib within a playground.

Any ideas how to do this? Thank you.
1 Like

Finally figured it out. I had to load the view controller as a UINib and instantiate it from the returned array as a UIViewController:

// Assuming the nib file is called "vc" I load it as a UINib
let nib = UINib(nibName: "vc", bundle: nil)

// Then instantiate it which returns an array
let nibArray = nib.instantiate(withOwner: nil, options: nil)

// Since there is one top level object which is a UIViewController...
let vc = nibArray.first as! UIViewController

// And finally display it in the playground
PlaygroundPage.current.liveView = vc
1 Like

hey, Do you ever try using a view nib ? I tried to register cell for collectionViewCell. but it did’t work.

let nib = UINib(nibName: "Cell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: "Cell")