Home > other >  Create custom ViewController from xib file is working?
Create custom ViewController from xib file is working?

Time:09-23

I am new to Swift. I have a CustomViewController.xib that links up to my CustomViewController. Outlets and all are connected.

Why is it that I am able to call CustomViewController() and able to have it presented with the outlets all working fine? I see lots of examples and supposedly it is to be CustomViewController(nibName: nil, bundle: nil).

Thank you.

CodePudding user response:

It looks like Apple made the "empty" initializer for view controllers smart, such that it will search for an XIB file that contains the view controller's views, and will open it if it follows the normal naming convention for view controller XIB files.

(either naming the XIB file with the exact same name as the VC class, or, if the class name ends with "ViewController", truncating that suffix to "View".)

See this article from Apple:

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621487-nibname

That is a discussion of the UIViewController nibName property. It says, in part:

If you use a nib file to store your view controller's view, it is recommended that you specify that nib file explicitly when initializing your view controller. However, if you do not specify a nib name, and do not override the loadView() method in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the .nib extension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:

I tried a test, and created a new view controller SecondViewController in a test Xcode project, checking "Also create XIB file". That named the XIB file "SecondViewController.xib". When I did that, I was able to instantiate the view controller using SecondViewController() and it loaded its views.

So it seems that what init(nibName:bundle:) does is to set the corresponding properties nibName and nibBundle on the view controller instance. Then when your view controller tries to load it's views, it attempts to open an XIB file as described above.

I'm actually surprised at this behavior. I've never been able to create a view controller from an XIB by just invoking it from its init() method.

  • Related