views:

269

answers:

2

I am in a situation where one of my ViewControllers has many special cases and I need an elegant way of handling them. The general idea is that the bottom half of my View is identical in each case. The top half changes for each case.

In accordance to DRY, I want to avoid make copies of my ViewController for each special case and changing the buttons at the bottom for every ViewController if I need to make a change. Usually, I create a .xib, build my UI in IB, and make my connections. I did this for the bottom half of the screen and it works fine.

For the top half of the screen, I created separate UIView instances separately. I hope to dynamically load those when before the ViewController appears (the docs tell me to use layoutSubviews, layoutIfNeeded, and setNeedsLayout).

The problem this design presents is that I am accustomed to making connections in IB with variables I have defined as IBOutlets. I follow the pattern of making variables properties in the header file to make them properties and using "synthesize" in the .m file. I'm also accustomed to the setting the delegate of UITextFields to the File's Owner so I can resign their first responder status on the keyboard.

If Interface Builder only allows me to access the File's Owner and IBOutlets in my given view, how do I access these properties in the superview that dynamically adds it? What is the proper design here?

Thanks in advance!

+3  A: 

It looks like adding a top view is your view controller's business. I would do that in the controller's -loadView after sending [super loadView]. There are two approaches to connecting them together at run time.

  1. Do it all programmatically, including allocating subviews, setting delegates, etc.
  2. Create all the top views in the same nib, connect them as needed and add an outlet for each top view to your view controller. Don't put any of the top views into your main view in IB. That way, when the controller loads the nib, it has all the top views loaded and correctly working and just has to install the right one as a subview to its main view.

Which method you prefer depends on how many top views you must handle, how difficult it is to set them up in code vs in IB and how long it takes your app to load a large nib with that many views.

Costique
A: 

You can reuse same view from XIB within different viewcontrollers. Your XIB should contain a single root object (View, not controller), that may be loaded and accessed from code:

myView = [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil] objectAtIndex:0];
vaddieg