cojoj
cojoj

Reputation: 6475

UIViewController inside XIB?

Currently I'm struggling with creating a subclass of UIViewController or UINavigationController with XIB file as a view.

When I create everything from the Xcode's menu (New File -> Class -> With Nib... etc.) I get a XIB but only with a plain UIView but I want UIViewController instead.

I read somewhere that XIBs are only for a views and you have to handle controller in code, is it true? Because as you can read here it's possible to insert Navigation Controller component into XIB. But I have one problem with the code from this tutorial - I get empty view with empty UINavigationBar. When I do the same with regular View Controller I get info abut this controller being used more than once...

I'm not trying to force Interface Builder to do something unusual but I want to know if this is possible (it would be easier and nicer to modify view controller component insted of a content view)? And if it is, how to achieve this?

Upvotes: 1

Views: 1315

Answers (2)

Stoyan
Stoyan

Reputation: 1315

I have just checked to confirm whether it is possible and to my surprise it is! You can have UIViewControllers inside Xibs

The test was done in XCode 10.1, Swift 4.2.

I have never used it before, but i thought since it gives you the option from the item library to pick view controllers, it has to be possible. I have added one to my xib, and just like in the storyboards, i have linked it with class, set IBOutlets and IBActions and it all worked perfectly fine.

The key thing is to instantiate it like this:

// Method inside the `UIViewController` you want to present our view controller from xib
// The xib file is `XibViewController.xib` and it has only one item inside - `UIViewController` with custom class set to `XibViewController`

guard let xibViewController = UINib(nibName: "XibViewController", bundle: nil).instantiate(withOwner: self, options: nil).first as? XibViewController else { return }

present(xibViewController, animated: true)

here you can find my test project: https://github.com/stoqn4opm/XibViewController

Upvotes: 2

Martin O'Shea
Martin O'Shea

Reputation: 432

An XIB file is used for building content that is viewable on a screen. A UIViewController is not viewable. It instead owns a view (which is viewable) created from an XIB or from code.

I think from what you are trying to do is use a storyboard which lets you visually layout your UIViewControllers to define there segue from each other (in your case in a Navigation Controller) which means show the next UIViewControllers view and put it in the UIViewController hierarchy.

Upvotes: 0

Related Questions