Using UIViewController Class Inheritance with Nib Files

If you’re like me, you love using .xib files to specify what your user interfaces are to look like. One unfortunate side effect of using .xib files is that they do not easily lend themselves to class inheritance. Described here is a technique for using class inheritance with your UI elements laid out in .xib files.

For this example, we have a class hierarchy that looks like this:

UIViewController (included in UIKit)




JMViewController can be though of as the root of our specific view controller class hierarchy. It contains a view, IBOutlets, UILabels, UIButtons, etc. It also has a method that is going to be used by the view controller cubclasses:

– (void)addSubviewsFromSuperclass;

This method gets called in the – (void)viewDidLoad method of the subclasses and does this following:

  1. Gets a pointer to the current self.view property
  2. Loads the nib of the superclass, connects all inherited IBOutlets, and gets the main view (element 0)
  3. Reassigns the self.view property (the loadNibNamed method assigned it to the main view of the nib)
  4. Adds all subviews of the nib’s main view to our current view hierarchy
  5. (all this happens in a try/catch block in case something goes wrong with the nib loading process)

So, basically, the way to use class hierarchy with UIViewControllers that use .xib files is to call a special method that will unpack the view hierarchy of the superclass and add all elements to the current instance.

Check out the example project here!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: