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:
This method gets called in the – (void)viewDidLoad method of the subclasses and does this following:
- Gets a pointer to the current self.view property
- Loads the nib of the superclass, connects all inherited IBOutlets, and gets the main view (element 0)
- Reassigns the self.view property (the loadNibNamed method assigned it to the main view of the nib)
- Adds all subviews of the nib’s main view to our current view hierarchy
- (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.