简体   繁体   中英

iOS viewDidLoad is not fired

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.

-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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM