以编程方式更改UINavigationController的根控制器

时间:2014-12-10 15:55:49

标签: ios uiviewcontroller uinavigationcontroller storyboard

我正在使用故事板,我已将UITabBarController设置为根控制器。我在标签栏中有3个标签项,对于第一个标签项,我有一个UINavigationController。我希望这个导航控制器的根视图控制器是动态设置的:我有两个视图控制器候选,具体取决于用户提供的参数。

我试图在AppDelegate中这样做:

UIStoryboard *storyboard = self.window.rootViewController.storyboard;
if (condition1) {
    UINavigationController *navViewController = [storyboard instantiateViewControllerWithIdentifier:@"navController"];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"homeController1"];
    [navViewController setViewControllers:@[viewController]];

} else if (condition2) {
    UINavigationController *navViewController = [storyboard instantiateViewControllerWithIdentifier:@"navController"];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"homeController2"];
    [navViewController setViewControllers:@[viewController]];

但它不起作用。在故事板中,我没有homeController1 nor homeController2`的任何segue。我怎么能这样做?

由于

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您将尝试根据条件启动不同的视图控制器。您可以在应用代理中尝试此操作。

UIStoryboard *storyboard =
  [UIStoryboard storyboardWithName:@"Main" bundle:nil];

if (yourCondition) {
    UIViewController *viewController =
    [storyboard instantiateViewControllerWithIdentifier:@"tutorialView"];
    self.window.rootViewController = viewController;
} else {
    UIViewController *viewController = [storyboard
        instantiateViewControllerWithIdentifier:@"mainViewController"];
    self.window.rootViewController = viewController;
}