0

In my app I am putting a sub view into a view:

subViewController = [[SubViewController alloc] init];
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"SubView" owner:subViewViewController options:nil];
UIView *view = [nibContents objectAtIndex:0];
view.frame = CGRectMake(2, 0, myView.frame.size.width - 4, myView.frame.size.height);
[myView addSubview:view];

But viewDidLoad inside SubViewController is never fired.

Here is the code:

- (void)viewDidLoad
{
  [super viewDidLoad];
   NSLog(@"ViewDidLoad");
}

In IB I have set files owner as SubViewController. I don't know where the problem is. Any ideas? Thank you.

Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
DanielH
  • 953
  • 10
  • 30
  • subViewController = [[SubViewController alloc] init]; that is the line where viewDidLoad would be called that doesn't solve your problem but it's a good place to start :D – A'sa Dickens May 24 '13 at 14:24
  • 1
    This is not true. viewDidLoad is not called on initialization. It is called when the view is first accessed or used. – drewag May 24 '13 at 14:25
  • IIRC, simply accessing the `view` property will force the view to load. – Hot Licks May 24 '13 at 14:30

2 Answers2

2

-viewDidLoad is not called because you are not executing any code to force it to load. A view controller's view is lazy loaded. If you try to access or do something with subViewController.view it will call viewDidLoad on the controller because it will create the view then.

drewag
  • 93,393
  • 28
  • 139
  • 128
0

Just adding UIViewControllers view to another view wont make it "active" and it won't receive viewDidLoad, viewDidAppear, viewDidDisappear nor others.

I would do this:

subViewController = [[SubViewController alloc] initWithNibName:@"SubView" bundle:nil];
subViewController.view.frame = CGRectMake(2, 0, myView.frame.size.width - 4, myView.frame.size.height);
[self addChildViewController:subViewController];
[self.view addSubview:subViewController.view];
[subViewController didMoveToParentViewController:self];
Valentin Solina
  • 309
  • 1
  • 7
  • 1
    your code will work but your explanation is a little off. The view is lazy loaded. It will be loaded immediately when it is accessed on the view controller and viewDidLoad will be called immediately afterwards. So in your code it will happen on the second line. – drewag May 24 '13 at 14:33
  • true but this will also solve future problems with other callbacks not being called (viewWillAppear, viewDidAppear, ...) :) – Valentin Solina May 24 '13 at 14:38
  • Agreed. I just want to make sure they understand the true nature of the problem and not just feed them code the solves the problem magically. – drewag May 24 '13 at 14:42
  • Thank you, now it works. But I don´t understand lines 3 an 5 in your code. It works without these two lines. Why it have to be there? – DanielH May 27 '13 at 06:55