如何在呈现之前设置根视图控制器的属性?

时间:2015-09-12 08:23:18

标签: ios uinavigationcontroller segue presentviewcontroller rootview

我在UINavigationController中有一个storyboard我从其他视图控制器以模态方式呈现:

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

此导航控制器已在UIViewController中将另一个storyboard设置为其根视图控制器。我想在显示之前为这个根视图控制器设置一些属性,但我尝试了这个:

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

但是当我尝试设置其属性时,根视图控制器似乎还没有被加载......

我怎么能这样做?感谢

1 个答案:

答案 0 :(得分:0)

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