iosuinavigationcontrollerseguepresentviewcontrollerrootview

How to set properties of a root view controller before being presented?


I have a certain UINavigationController in storyboard I present modally from another view controller:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UINavigationController *myNavController = [storyboard instantiateViewControllerWithIdentifier:@"myNavController"];
[self presentViewController:myNavController animated:YES completion:nil];

This navigation controller has set another UIViewController as its root view controller in storyboard. I'd like to set some properties for this root view controller before it is shown, but I tried this:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UINavigationController *myNavController = [storyboard instantiateViewControllerWithIdentifier:@"myNavController"];
[self presentViewController:myNavController animated:YES completion:nil];
 MyRootViewController *myRootViewController = [storyboard instantiateViewControllerWithIdentifier:@"myRootViewController"];
[myRootViewController setSelectedItem:selectedItem];
[myRootViewController setDelegate:self];

But the root view controller doesn't seem to be loaded yet when I try to set its properties...

How could I do this? Thanks


Solution

  • If you had debugged, you will find the myRootViewController made by MyRootViewController *myRootViewController = [storyboard instantiateViewControllerWithIdentifier:@"myRootViewController"]; isn't the myNavController's real rootViewController.

    This method -instantiateViewControllerWithIdentifier: just give you a whole new UIViewController instance.

    So, If you want get the real rootViewController, just replace it with following:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UINavigationController *myNavController = [storyboard instantiateViewControllerWithIdentifier:@"myNavController"];
    
     MyRootViewController *myRootViewController = myNavController.viewControllers[0];
    [myRootViewController setSelectedItem:selectedItem];
    [myRootViewController setDelegate:self];
    
    [self presentViewController:myNavController animated:YES completion:nil];