将viewController设置为root viewController的正确方法

时间:2016-07-20 04:39:39

标签: ios swift cocoa-touch

在你有一个viewController的场景中,你希望以root视图的形式呈现在其他所有内容上的正确方法是什么?

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?以及在什么情况下呢?使用其中一个的优点/缺点是什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)