如何在appdelegate中控制视图控制器?

时间:2016-01-05 07:47:30

标签: ios objective-c appdelegate

我真正构建了这个简单的问题。

我只是使用以下代码从一个视图控制器移动到另一个视图控制器。

homescreen *home;
home=[self.storyboard instantiateViewControllerWithIdentifier:@"home"];
[self presentViewController:home animated:YES completion:nil];

AppDelegate方法中尝试使用相同的代码。

UIStoryboard *storyboard;
sur= [storyboard instantiateViewControllerWithIdentifier:@"survey"];
[self.window.rootViewController presentViewController:sur animated:YES completion:nil];

当我使用此代码时,我遇到了这个崩溃:

  

由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:'应用程序尝试在目标上显示nil模态视图控制器

我不想让它成为根视图控制器,只需要移动它。

5 个答案:

答案 0 :(得分:3)

您只声明UIStoryboard *storyboard未初始化它,在下一行中,您在nil对象上调用方法instantiateViewControllerWithIdentifier。最终storyboard变量在以下行和崩溃中替换nil。

sur= [storyboard instantiateViewControllerWithIdentifier:@"survey"];

答案 1 :(得分:3)

您无法直接在空的window.rootViewController上显示视图。您需要先将其设置为任何viewController,然后显示需要显示的viewController。请参阅此代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    InitialViewController *initialVC = [storyboard instantiateViewControllerWithIdentifier:@"InitialViewController"];
    self.window.rootViewController = initialVC;
    [self.window makeKeyAndVisible];

    ShowThisViewController *showThisVC = [storyboard instantiateViewControllerWithIdentifier:@"ShowThisViewController"];
    [self.window.rootViewController presentViewController:showThisVC animated:YES completion:nil];

    return YES; }

答案 2 :(得分:1)

访问this

我认为Aamir是对的。但是,此外,您需要使窗口可见。

您需要致电

[self.window makeKeyAndVisible];

在呈现任何ViewController之前。

答案 3 :(得分:1)

使用此代码

    DEMORootViewController *VerifyV = [self.storyboard  instantiateViewControllerWithIdentifier:@"Identifier"];  

   UINavigationController *navigationController=[[UINavigationController alloc]initWithRootViewController:VerifyV];

    self.window.rootViewController = navigationController;

答案 4 :(得分:0)

只需尝试以下代码:

UIStoryboard *storyboard;
survey *sur= [storyboard instantiateViewControllerWithIdentifier:@"survey"];
UIViewController *curViewCont = [UIApplication sharedApplication].keyWindow.rootViewController;
while (curViewCont.presentedViewController) {
    curViewCont = curViewCont.presentedViewController;
}
[curViewCont presentViewController:sur animated:YES completion:nil];

希望它对你有用。

相关问题