Loading views from XIB’s on iOS

Daniel Lozano Valdés
Sudo by Icalia Labs
2 min readJan 3, 2017

Before storyboards were prevalent, iOS developers created Views programatically or loaded them from a XIB (sometimes called nib) file. Which is a simpler interface builder file that does not have all the features of a storyboard.

But still today you will want to use XIB’s for some cases when storyboards are too much. Unfortunately loading from XIB’s can be confusing sometimes as there are several ways to do so.

That’s why I created these extensions to make it a little bit easier and less error-prone.

Loading a View Controller’s view from a XIB file

Doing this is pretty simple:

let viewController = MyViewController(nibName: "MyViewController", bundle: nil)

But the information needed to load this View Controller is outside the class itself, and it’s using a String which can be error prone. That’s why I prefer to do this in an extension on UIViewController, like so:

All I’m doing here is getting a String representation of the View Controller’s Class, and also getting the Bundle for that same class (in case we are inside a framework or extension). Then I’m loading the nib and returning it.

Then inside my UIViewController subclass all I would need to do is override the loadView() method, and set the view property.

Afterwards, loading my View Controller can be as simple as this:

let viewController = MyViewController()

Loading a custom UIView subclass from a XIB file

Loading a View from a XIB file is usually a little more complicated because there are several ways to do so. But I like to do it with an extension on UIView, like so:

The loadFromNib() method is similar to my previous method on the UIViewController extension. But this one is a little more complicated, because instead of returning the View, it goes ahead and adds it as a subview and sets it’s constraints, so that my all my custom UIView subclasses don’t have to add that boiler-plate code.

Then you can create a UIView subclass, and use it like so:

Things to consider

  • Remember to create your XIB file and set the “File’s Owner” to your UIView or UIViewController subclass.
  • The name of your XIB file must be the same name as your subclass. That’s because the name the extension uses to load the XIB is the String representation of the subclass.
  • This is the way I do it and it’s worked great for me. But if you have any improvements, or questions feel free to ask in the comments.

--

--