Ios – How to create view controller that is defined in XIB

interface-builderiosios7uiviewcontroller

Sorry for perhaps noob question, guys. I'm new to iOS development.

How can I create view controller that is defined in XIB ?

When you create new class inherited from UIViewController in Xcode via "New File" and mark with XIB checkbox it creates xib file that doesn't have viewController element. But rather it has placeholder which points to UIViewController which is defined in the code.

But I see that you can create controller itself in Interface Builder and specify customClass for it.

Unfortunately it doesn't work for me. I get loaded the "EmbeddedViewController" nib but the view outlet was not set error in run-time. But I believed view property must be set by resource loader automatically since everything is defined via XIB. It works that way for TableView and its cells for example.

Could you please provide example how to do it ?

I created sample project: https://github.com/cppexpert/SampleWithNib

The controller in question is EmbeddedViewController

Best Answer

Create one Xib per UIViewController

Each Xib have File's Owner object for you to set UIViewController class there. Click File's Owner and choose EmbeddedViewController on it's class

Then drag main UIView not UIViewController class to there, then hook up this view with file's owner as view. UIViewController just use to drag to StoryBoard base project.

https://github.com/lequysang/gitfiles02/blob/master/SampleWithNib-master.zip