-
Notifications
You must be signed in to change notification settings - Fork 85
Nib loading helpers
UIKit+PivotalCore adds categories on UIView and UIViewController which aim to make it easier to load nib-based classes from other nibs.
To use this functionality, a few steps are required:
For views which have a nib as well as an implementation (for instance, with outlets or actions bound back to the instance)
- Lay out your containing view's nib, and place a placeholder view for the class you want to instantiate
- Edit the view's class to be the class you want to load
- Ensure the class you want to load has a nib with the same name as the class (e.g. FooClass.{h,m} has a corresponding nib FooClass.xib, FooClass~iphone.xib, or FooClass~ipad.xib)
- Set it up with autolayout constraints if appropriate
- Give the view a unique restoration identifier beginning with "placeholder" (e.g. "placeholder-FooClass")
When this nib is loaded, the view will be correctly instantiated with its inner bindings and constraints set up, preserving its outer bindings and constraints. This aims to make it easier to reuse view classes with nibs as well as implementation files in larger projects.
For example, say you have a view class ReusedView:
ReusedView has a ReusedView.xib with some layout and bindings that you want to re-use:
To load ReusedView.xib from within MainController's xib you set up MainController's xib as follows:
The placeholder view is replaced by the view specified by ReusedView.xib. The binding of the ReusedView instance to the MainController's reusedView property declared in MainController.xib is maintained with the replacing instance:
It is also possible to load a child view controller's nib-based view from a parent view controller's nib. In order to do this you need to:
- Add a child view controller to the parent view controller's nib
- Add a placeholder view in the parent view controller's nib
- Assign the placeholder view to the child controller's view outlet
- Give the placeholder view a unique restoration identifier beginning with "placeholder"
- Add the following lines of code in the parent view controller's viewDidLoad
[self addChildViewController:self.childViewController];
[self.childViewController didMoveToParentViewController:self];
For example, with ChildViewController's nib that looks like this:
Set up the containing view controller with a nib like this (where the child view controller's class is set to ChildViewController):
The placeholder view bound as ChildViewController's view in MainController's nib will be replaced by the view specified in ChildViewController.xib. All of the bindings in ChildViewController.xib and all of the layout specified in MainController's nib will be maintained: