简体   繁体   中英

viewDidLoad and ViewDidAppear not being called

I have a UIViewController that is being created from a xib file.

I initialise it like this:

 _sharedSingleton = [[SlipChangesViewController alloc] init];
            [[NSBundle mainBundle] loadNibNamed:@"SlipChangesViewController" owner:_sharedSingleton options:nil];

I add the view of that UIViewController to the subview in another UIViewController:

[self.view addSubview:slipChangesVC.view];

Now the weird thing is, the view is successfully added to the subview, but for some reason both viewDidLoad and vieWillAppear are not called. It is however successfully calling the method to create the shared singleton and the init method.

I have double checked to make sure:

  • None of the UIViews or UIViewControllers are nil
  • The outlets from the xib are correctly linked
  • I am calling [super viewDidLoad] and [super viewWillAppear]

I have check various threads on stackOverflow and tried there suggestions with no success. eg. Calling [slipChangesVC view]

Does anyone know why these 2 methods would not be called?

This is not the right way of adding child view controller. In this way, view owner gets changes. View detached from its view controller and view controller stops receiving viewDidLoad and other view methods.

If you want to make it work, please look into already answered question: add UIViewController in subview

You are adding a SlipChangesViewController view over existing view. In that case viewDidLoad and viewWillAppear never called. You need to add a ViewController for this

try this one

- (void)addChildViewC:(UIViewController *)childViewC
{
    [self addChildViewController:childViewC];
    childViewC.view.frame = self.view.bounds;
    [self.view addSubview:childViewC.view];
    [childViewC didMoveToParentViewController:self];
}

I would never make a view controller a singleton. It's not a singleton. It gets created, destroyed, created again, destroyed again.

I think viewDidLoad is only called once during the lifetime of a view controller. So making yours a singleton could cause all kinds of problems.

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