使用AppDelegate中的Storyboard以编程方式实例

使用AppDelegate中的Storyboard以编程方式实例

本文介绍了使用AppDelegate中的Storyboard以编程方式实例化View Controller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在忙着构建一个应用程序 - 当它第一次启动它时会要求用户做两件事:

I'm busy building an app - that when launched for the first time it asks the user to do two things:


  1. 选择国家

  2. 接受T& Cs

从那里进入家庭视图控制器。

From there it goes to the home view controller.

我目前面临的问题是将第一个视图控制器从我的应用代表推送到屏幕上。我正在使用故事板/ Xcode 5 / iOS7

The problem I am currently facing is pushing the first view controller onto the screen from my app delegate. I'm using storyboards / Xcode 5/ iOS7

以下是我提出的代码:

UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle: nil];
BBCounterySettingsViewController *controller = (BBCounterySettingsViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"CountrySettings"];
[navigationController pushViewController:controller animated:NO];

问题是应用程序在遇到最后一行代码时崩溃,并出现以下错误:

The problem is the app crashes when it hits the last line of code with the following error:

任何人都有任何想法我做错了什么?

Anyone have any ideas what I am doing wrong?

推荐答案

你期望 self.window.rootViewController 成为 UINavigationController 但它是 UIViewController 。这意味着故事板中最外层的视图控制器类型错误。

You're expecting the self.window.rootViewController to be a UINavigationController but it's a UIViewController. This means that the outermost view controller in your storyboard is of the wrong type.

获取 UINavigationController的更好方法(在这种情况下应该适用)是在任何 UIViewController 上使用属性 self.navigationController

A better way to obtain the UINavigationController (Which should work in this case) is to use the property self.navigationController on any UIViewController.

根据我的理解,您希望在用户第一次运行时让用户选择一些内容。你应该做的是提供一个模态视图控制器,如下所示:

From what I understand you want to present a view the first time the user runs to have the user pick some stuff. What you should then do is present a modal view controller, like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//isFirstRun is some boolean you use to determine if it's the first run
if(isFirstRun){
    BBCounterySettingsViewController *controller = (BBCounterySettingsViewController *)[mainStoryboard instantiateViewControllerWithIdentifier: @"CountrySettings"];
    [self.window.rootViewController presentViewController: controller animated:YES completion:nil];
}

这篇关于使用AppDelegate中的Storyboard以编程方式实例化View Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:47