Can a View Controller manage more than 1 nib based view?
- by Hugo Brynjar
I have a VC controlling a screen of content that has 2 modes; a normal mode and an edit mode.
Can I create a single VC with 2 views, each from separate nibs?
In many situations on the iphone, you have a VC which controls an associated view. Then on
a button press or other event, a new VC is loaded and its view becomes the top level view etc.
But in this situation, I have 2 modes that I want to use the same
VC for, because they are closely related. So I want a VC which can swap in/out 2 views.
As per here:
http://stackoverflow.com/questions/863321/iphone-how-to-load-a-view-using-a-nib-file-created-with-interface-builder/2683153#2683153
I have found that I can load a VC with an associated view from a nib and then later on load
a different view from another nib and make that new view the active view.
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EditMode" owner:self options:nil];
UIView *theEditView = [nibObjects objectAtIndex:0];
self.editView = theEditView;
[self.view addSubview:theEditView];
The secondary nib has outlets wired up to the VC like the primary nib. When the new nib is loaded,
the outlets are all connected up fine and everything works nicely. Unfortunately when this edit
view is then removed, there doesn't seem to be any elegant way of getting the outlets hooked up
again to the (normal mode) view from the original nib. Nib loading and outlet setting seems a
once only thing.
So, if you want to have a VC that swaps in/out 2 views without creating a new VC, what are the options?
1) You can do everything in code, but I want to use nibs because it makes creating the UI simpler.
2) You have 1 nib for your VC and just hide/show elements using the hidden property of UIView and its subclasses.
3) You load a new nib as described above. This is fine for the new nib, but how do you sort the outlets when you go back to the original nib.
4) Give up and accept having a 1:1 between VCs and nibs. There is a nib for normal mode, a nib for edit mode and each mode has a VC that subclasses a common superclass.
In the end, I went with 4) and it works, but requires a fair amount of extra work, because I have a model class that I instantiate in normal mode and then have to pass to the edit mode VC because both modes need access to the model. I'm also using NSTimer and have to start and stop the timer in each mode. It is because of all this shared functionality that I wanted a single VC with 2 nibs in the first place.