2016-07-20 63 views
1

在您想要以超級視圖的形式呈現視圖控制器的場景中,一切正確的方法是什麼?將viewController設置爲根視圖控制器的正確方法

let Storyboard = UIStoryboard.init(name: "Main", bundle: nil) 
let MY_VIEW = Storyboard.instantiateViewControllerWithIdentifier("VIEWID") 


//Is this the right way? 
UIApplication.sharedApplication().delegate.window?.rootViewController?.presentViewController(MY_VIEW, animated: true, completion: nil) 


//Or this?  
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(MY_VIEW, animated: true, completion: nil) 

在你爲什麼要使用UIApplication.sharedApplication().delegate.window?超過UIApplication.sharedApplication().keyWindow?.rootViewController?以及在什麼情況下換句話說?使用一個或另一個的優點/缺點是什麼?

+1

讀區別:(http://stackoverflow.com/questions/21698482/diffrence- [中keyWindow門窗diffrences] UIApplication的間-sharedapplication-代表窗口和-U) – Chandan

回答

1

您可以按照以下步驟操作。

let rootController = storyboard.instantiateViewControllerWithIdentifier("VIEWID") as! SplashVC 

     if self.window != nil { 
      self.window!.rootViewController = rootController 
     } 

當窗口爲零時,這樣做的好處是不會崩潰。

另一種方法是(最安全的方式,我認爲)

let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController 
    let rootViewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("VIEWID") as! LoginVC 
    navigationController.viewControllers = [rootViewController] 
    self.window?.rootViewController = navigationController 
0
  let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      let viewController: MainViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController 

      let rootViewController = self.window!.rootViewController as! UINavigationController 
      rootViewController.pushViewController(viewController, animated: true) 
相關問題