views:

3286

answers:

2

I have a tabview controller to which I added a UIViewController to each tab. I want to have multiple UIViews inside the UIViewController.

So in the implementation of the UIViewController class I added [self.view addSubView:uiview1] and [self.view addSubView:uiview2]. The problem is that when I run the app, it crahes on load.

However, if I only used a single UIView and did: self.view = UIView1 that would work fine.

Does anyone know what is causing the problem? Or if I'm doing something fundamentally wrong?

+1  A: 

There's no reason you can't have multiple views within your UIViewController's main view member variable. However, there are quite a few items left unanswered in your question:

  • How are you obtaining view1 and view2?
  • Are they outlets in your XIB file (are you using a XIB file, or creating everything in code), or are you creating them in code?
  • Where in your UIViewController subclass are you adding them to your view member variable?
  • What's the message printed to the console when it crashes?
Ben Gottlieb
+1  A: 

Assuming you are doing this programmatically, you're supposed to create the view in the view controller's loadView method. So you must do this:

self.view = [[[UIView alloc] initWithFrame:someFrame] autorelease];

before you do this:

[self.view addSubview:uiview1];
[self.view addSubview:uiview2];

Otherwise, self.view would be nil.

Mike McMaster
That's not really true. A UIViewController's view IS created for you for free, provided you do not override -(void)loadView.Just add the subviews in -(void)viewDidLoad.
Amagrammer
I guess you're right, though that goes against Apple's recommendation. UIViewContoller's documentation for the loadView method specifically says you should override that method to initialize your views when creating them manually.
Mike McMaster