Reputation: 569
I am unclear on how to reuse view controllers. If you have created a view controller subclass that does some stuff (doesn't really matter what it does, just that it does what you need in the view), can it be used with a different view or should it be subclassed again?
In other words, if I need the exact same functionality in a view in a different part of my app, can I use the original view controller and just add the outlets from the new view? Or should I subclass the custom controller and give the view its "own" view controller?
Upvotes: 1
Views: 2871
Reputation: 77621
You could create two xibs for the view controller.
If you have the files...
MyViewController.m
MyViewController.h
Then you could add the xibs...
MyViewControllerXib1
MyViewControllerXib2
Just make the "File's Owner" MyViewController.
Then when you need the UI layout from the first XIB you can call...
MyViewController *controller = [[MyViewController alloc] initWithNibName:@"MyViewControllerXib1" bundle:[NSBundle mainBundle]];
When you need the second UI you can call...
MyViewController *controller = [[MyViewController alloc] initWithNibName:@"MyViewControllerXib2" bundle:[NSBundle mainBundle]];
The object you get will be the same but the nib laying out the UI will change.
ANOTHER APPROACH
Just thinking out loud here.
You could also create a ViewController without a nib.
Then create two subclasses of this each WITH a nib. Now you have code reuse and separate layouts but you can also make fine control tweaks to each of the subclasses of your "master" controller.
You can then create as many subclasses as you like from this master view controller.
USING STORYBOARDS
Just drag a new ViewController object onto the storyboard. Change the class to be the view controller class and set up the UI and drag the controls to the code etc... You will then have two screens that look different but share the same functionality code.
This is just the same as what I said at first but using storyboard instead.
Upvotes: 3