2013-12-12 88 views
10

實例化視圖控制器編程我正忙着建立一個應用程序 - 這是第一次啓動時,它要求用戶做兩件事情:用故事板從AppDelegate中

  1. 選擇一個國家
  2. 接受ŧ & Cs

從那裏它轉到主視圖控制器。

我目前面臨的問題是從我的應用程序委託將第一個視圖控制器推到屏幕上。我使用的是故事板/ 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]; 

的問題是應用程序崩潰,當它擊中的代碼的最後一行,出現以下錯誤:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController pushViewController:animated:]: unrecognized selector sent to instance 0x8e9a400'

任何人有任何想法我做錯了什麼?

回答

11

您期待self.window.rootViewControllerUINavigationController,但它是UIViewController。這意味着故事板中最外面的視圖控制器的類型是錯誤的。

獲得UINavigationController(在這種情況下應該起作用)的更好方法是在任何UIViewController上使用屬性self.navigationController

根據我的理解,您希望在用戶第一次運行時提供視圖,讓用戶選擇一些內容。目前什麼,那麼你應該做的是一個模式視圖控制器,這樣的:

- (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]; 
} 
+0

我想我正在採取這種方法錯誤的方式。這個視圖控制器不需要在其他地方導航。只需要被解僱。該應用程序的其餘部分是基於標籤欄的應用程序。在應用程序委託self.navigationController不存在? – Tander

+0

我會用新的提示更新我的答案然後:) – Rick

7

有兩件事情你需要做的:

  1. 在故事板,你所提到的控制器名稱(如LoginView),並允許使用故事板ID
  2. 然後你有用戶以下行

    loginView = [storyboard instantiateViewControllerWithIdentifier:@"LoginView"]; 
    [(UINavigationController*)self.window.rootViewController pushViewController:loginView animated:NO]; 
    

希望這會有所幫助。讓我知道你是否仍然有這個問題。

+0

感謝這也有幫助。 – Tander

+0

如果在一些UINavigationController中嵌入了你的viewController,你也可以使用'instantiateInitialViewController()'方法'UIStoryBoard'。這會自動加載在故事板上標有箭頭的viewController。如果這個viewController是一個容器,它的孩子也會加載。 – Vinzzz

0
[self performSegueWithIdentifier:@"buyListSegue" sender:sender]; 
+1

這個答案可以做一些解釋... –

+0

沒有幫助。 Segges不能從AppDelegate或viewControllers發生UINavigationController的任何部分 – Tander

0

我認爲控制器標識"CountrySettings"被設置爲錯誤的控制器。你沒有得到一個NavigationController你可以撥打pushViewController ...

+0

解決了這個問題,謝謝。明顯的答案是這個問題。 – Tander