How to install rootViewController using Swift, iOS 7

I want to install rootViewController in the application delegate.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

     var rootView: MyRootViewController = MyRootViewController()
     //Code to set this viewController as the root view??


     return true

}
+24
source share
5 answers

You can do something like this.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

     var rootView: MyRootViewController = MyRootViewController()

     if let window = self.window{
            window.rootViewController = rootView
     }

     return true
}
+26
source

If you are using a storyboard and want to programmatically configure rootViewController, first make sure the ViewController has a storyboard identifier in the identity inspector. Then in AppDelegate do the following:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

   // get your storyboard
   let storyboard = UIStoryboard(name: "Main", bundle: nil)

   // instantiate your desired ViewController
   let rootController = storyboard.instantiateViewControllerWithIdentifier("MyViewController") as! UIViewController

   // Because self.window is an optional you should check it value first and assign your rootViewController
   if let window = self.window {
      window.rootViewController = rootController
   }

   return true
}
+44
source

Swift 2.0:

var window: UIWindow?
 var storyboard:UIStoryboard?

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

  window =  UIWindow(frame: UIScreen.mainScreen().bounds)
  window?.makeKeyAndVisible()

  storyboard = UIStoryboard(name: "Main", bundle: nil)
  let rootController = storyboard!.instantiateViewControllerWithIdentifier("secondVCID")

  if let window = self.window {
   window.rootViewController = rootController
  }
+14

To show what you need to do if you are not using a storyboard. Inside AppDelegate inside the application function.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    let frame = UIScreen.mainScreen().bounds
    window = UIWindow(frame: frame)

    let itemsViewControler: UITableViewController = BNRItemsViewController()
    if let window = self.window{
        window.rootViewController = itemsViewControler
        window.makeKeyAndVisible()
    }

    return true
}
+11
source
   if let tabBarController = self.window!.rootViewController as? UITabBarController
    {
        tabBarController.selectedIndex = 0
    }
0
source

All Articles