September 17, 2010 1

Post-A-Day #2-Nib Aware View

By admin in Uncategorized

Apple recommends that if you have one screen, you have one instance of UIViewController, in there documentation “View Controller Programming”.

If you want to divide a single screen into multiple areas and manage each one separately, use generic controller objects (custom objects descending from NSObject) instead of view controller objects to manage each subsection of the screen. Then use a single view controller object to manage the generic controller objects. The view controller coordinates the overall screen interactions but forwards messages as needed to the generic controller objects it manages.

In short, one screen/one UIViewController.
So how can you design using interface builder the different parts of that screen in a more modular way. For example you want to have a front/back view a futury-baseball card that has buttons and scrollable text.

The preferred way for designing building such an interface, is to use ahem, interface builder.
“But only UIViewControllers can load NIB files!” – you say. It’s true, it’s true.

However you can design your UIView in interface builder very simply following these steps.

1. Create a new interface builder file in your project, using the View XIB template.
2. Design as you like, make sure that your class that is tied to it has the proper IBOutlets.
3. Make the “File’s Owner” is of your XIB file, class “UIViewController” (NOT A SUBCLASS!).
4. Make the View in the XIB file, the UIView subclass you have created.

Now you can load your view into your ( for example ), RootViewController like this

// In RootViewController for example
NSArray* nibViewsWithMatchingName =  [[NSBundle mainBundle] loadNibNamed:@"MyXIBFileNameWithoutExtention" owner:self options:nil];
// This array actually only contains our single object
NibAwareView* aView = [nibViewsWithMatchingName objectAtIndex: 0];
[self.view addSubview: aView];
[aView release];

That’s all there is to it, and your Interface Builder designed, XIB file will be loaded into your UIViewController instance

Tags: , , ,

One Response to “Post-A-Day #2-Nib Aware View”

  1. Sivakumar says:

    Wonderful post. Considering my application in which the screen is occupied by 4 views. I`m having a NSObject as the view controller. My questions are

    1)If I use a view controller the event is passed to the view controller automatically if it is received by the view. Is there any way this can happen automatically if I have NSobject as View controller

    2) I`m using a reference of the view controller in the view to pass the events from the view to the viewcontroller. Is this allowed according the MVC framework.

    Can you guys please help me.

Leave a Reply

Powered by WP Hashcash

Spam protection by WP Captcha-Free