views:

24145

answers:

7

Hi

I'm trying to do something a bit elaborate but that should be possible, so here is a challenge for all you experts out there (this forum is pack of the lot of you :) ).

Im creating a Questionnaire "component" I want to load on a NavigationContoller my QuestionManagerViewController. This is an "empty" view controller that can load different views depending on the question that needs to be answered.

The way I'm doing this is:

  1. Create the Question1View object a as UIView subclass, defining some IBOutlets.
  2. Create (using Interface Builder) the Question1View.xib (HERE IS WHERE MY PROBLEM PROBABLY ARE). I set the both the ViewController and the View to be of class Question1View.
  3. I link the outlets with the view's component (using IB).
  4. I override the inithWithNib of my QuestionManagerViewController to look like this:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
        if (self = [super initWithNibName:@"Question1View" bundle:nibBundleOrNil]) {
            // Custom initialization
        }
        return self;
    }
    

When I run the code Im getting this error:

2009-05-14 15:05:37.152 iMobiDines[17148:20b] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "Question1View" nib but the view outlet was not set.'

Im sure there is a way to load the view using the nib file, without needing to create a viewController class.

Any ideas?

Thanks!

Gonso

+8  A: 

You should not be setting the class of your view controller to be a subclass of UIView in Interface Builder. That is most definitely at least part of your problem. Leave that as either UIViewController, some subclass of it, or some other custom class you have.

As for loading only a view from a xib, I was under the assumption that you had to have some sort of view controller (even if it doesn't extend UIViewController, which may be too heavyweight for your needs) set as the File's Owner in Interface Builder if you want to use it to define your interface. I did a little research to confirm this as well. This is because otherwise there would be no way to access any of the interface elements in the UIView, nor would there be a way to have your own methods in code be triggered by events.

If you use a UIViewController as your File's Owner for your views, you can just use initWithNibName:bundle: to load it and get the view controller object back. In IB, make sure you set the view outlet to the view with your interface in the xib. If you use some other type of object as your File's Owner, you'll need to use NSBundle's loadNibNamed:owner:options: method to load the nib, passing an instance of File's Owner to the method. All its properties will be set properly according to the outlets you define in IB.

Marc W
One point, I believe that this view controller *should* be based in some manner on UIViewController to take advantage of all its functionality.Also, you don't *have* to make the File's Owner to a view controller. One can simply load the nib and grab the view out of that nib -- I don't have the code here but I know you can do it.
Lyndsey Ferguson
That's what I was trying to research. Everything I found indicated that there needs to be some sort of File's Owner linked to the view in order to access it. You could of course write something more hackish that iterated over the top-level objects in the nib and extract the view that way, but I was trying to stay away from suggesting that.
Marc W
I'm reading the Apress book, "Beginning iPhone Development: Exploring the iPhone SDK" and they discussed this method at chapter 9: Navigation Controllers and Table Views. It didn't seem too complicated.
Lyndsey Ferguson
I'd be curious to see how they say it's done. I don't have a copy of that book at the moment.
Marc W
You could always ping Jeff LaMarche or Dave Mark via Twitter. Can't remember the latter's handle offhand, but Jeff is @jeff_lamarche.
Jim Dovey
+12  A: 

Thank you all. I did found a way to do what I wanted.

  1. Create you UIView with the IBOutlets you need.
  2. Create the xib in IB, design it to you liking and link it like this: The File's Owner is of class UIViewController (No custom subclass, but the "real" one). The File Owner's view is connected to the main view and its class is declared as the one from step 1).
  3. Connect your controls with the IBOutltes.
  4. The DynamicViewController can run its logic to decide what view/xib to load. Once its made the decission, in the loadView method put something like this:

    NSArray* nibViews =  [[NSBundle mainBundle] loadNibNamed:@"QPickOneView" owner:self options:nil];
    QPickOneView* myView = [ nibViews objectAtIndex: 1];
    myView.question = question;
    

That's it!

The main bundle's loadNibNamed method will take care of initializing the view and create the connections.

Now the ViewController can display a view or another depending on the data in memory, and the "parent" screen doesn't need to be bother with this logic.

Gonso

I have a very similar problem - I simply want to load a UIView from an xib file. These steps don't work for me - the app crashes with "bad access" soon after adding the loaded view as a subview.
Justicle
For iPhone 3.0, use objectAtIndex:0 to get the first element.This crashes for me exactly as described by Justicle. Any idea why?
brainfsck
+1 it worked perfectly for me. I wanted to add multiple views that had the one view controller (im using a flip view scenario where a section of the view spins) I had to make the index on the array 0 (iPhone 3.0)
Aran Mulholland
This is the correct answer, however, the code should be modified so that it loops through nibViews and does a class check on each object, so that way you are certainly getting the correct object. objectAtIndex:1 is a dangerous assumption.
Jasconius
+2  A: 

The previous answer does not take into account a change in the NIB (XIB) structure that occurred between 2.0 and 2.1 of the iPhone SDK. User contents now start at index 0 instead of 1.

You can use the 2.1 macro which is valid for all version 2.1 and above (that's two underscores before IPHONE:

 // Cited from previous example
 NSArray* nibViews =  [[NSBundle mainBundle] loadNibNamed:@"QPickOneView" owner:self options:nil];
 int startIndex;
 #ifdef __IPHONE_2_1
 startIndex = 0;
 #else
 startIndex = 1;
 #endif
 QPickOneView* myView = [ nibViews objectAtIndex: startIndex];
 myView.question = question;

We use a technique similar to this for most of our applications.

Barney

Barney Mattox
A: 

I found this blog posting by Aaron Hillegass (author, instructor, Cocoa ninja) to be very enlightening. Even if you don't adopt his modified approach to loading NIB files through a designated initializer you will probably at least get a better understanding of the process that's going on. I've been using this method lately to great success!

Meltemi
+2  A: 

I too wanted to do something similar, this is what I found: (SDK 3.1.3)

I have a view controller A (itself owned by a Nav controller) which loads VC B on a button press:

In AViewController.m

BViewController *bController = [[BViewController alloc] initWithNibName:@"Bnib" bundle:nil];
[self.navigationController pushViewController:bController animated:YES];
[bController release];

Now VC B has its interface from Bnib, but when a button is pressed, I want to go to an 'edit mode' which has a separate UI from a different nib, but I don't want a new VC for the edit mode, I want the new nib to be associated with my existing B VC.

So, in BViewController.m (in button press method)

NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EditMode" owner:self options:nil];
UIView *theEditView = [nibObjects objectAtIndex:0];
self.editView = theEditView;
[self.view addSubview:theEditView];

Then on another button press (to exit edit mode):

[editView removeFromSuperview];

and I'm back to my original Bnib.

This works fine, but note my EditMode.nib has only 1 top level obj in it, a UIView obj. It doesn't matter whether the File's Owner in this nib is set as BViewController or the default NSObject, BUT make sure the View Outlet in the File's Owner is NOT set to anything. If it is, then I get a exc_bad_access crash and xcode proceeds to load 6677 stack frames showing an internal UIView method repeatedly called... so looks like an infinite loop. (The View Outlet IS set in my original Bnib however)

Hope this helps.

Brynjar
Reading between the lines, this helped me out too.
petert
+4  A: 

I'm not sure what some of the answers are talking about, but I need to put this answer here for when I search in Google next time. Keywords: "How to load a UIView from a nib" or "How to load a UIView from an NSBundle."

Here's the code almost 100% straight up from the Apress Beginning iPhone 3 book (page 247, "Using The New Table View Cell"):

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:@"Blah"
                                                 owner:self options:nil];
    Blah *blah;
    for (id object in bundle) {
        if ([object isKindOfClass:[Blah class]])
            blah = (Blah *)object;
    }   

    [self.view addSubview: blah];
} 

This supposes you have a UIView subclass called Blah, a nib called Blah which contains a UIView which has its class set to Blah.

Yar
If you use the `isKindOf` you are protected from Bundle structure changes.
Yar
+1  A: 

There is also an easier way to access the view instead of dealing with the nib as an array.

1) Create a custom View subclass with any outlets that you want to have access to later. --MyView

2) in the UIViewController that you want to load and handle the nib, create an IBOutlet property that will hold the loaded nib's view, for instance

in MyViewController (a UIViewController subclass)

  @property (nonatomic, retain) IBOutlet UIView *myViewFromNib;

(dont forget to synthesize it and release it in your .m file)

3) open your nib (we'll call it 'myViewNib.xib') in IB, set you file's Owner to MyViewController

4) now connect your file's Owner outlet myViewFromNib to the main view in the nib.

5) Now in MyViewController, write the following line:

[[NSBundle mainBundle] loadNibNamed:@"myViewNib" owner:self options:nil];

Now as soon as you do that, calling your property "self.myViewFromNib" will give you access to the view from your nib!

AVeryDev