web-dev-qa-db-fra.com

Comment configurer rootViewController avec Swift, iOS 7

Je souhaite définir rootViewController dans le délégué de l'application.

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

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


     return true

}
26
Stephen Fox

Vous pouvez faire quelque chose comme ça.

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

     var rootView: MyRootViewController = MyRootViewController()

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

     return true
}
31
Connor

Si vous utilisez un storyboard et souhaitez définir votre rootViewController par programme, assurez-vous d'abord que ViewController a un ID de storyboard dans l'inspecteur d'identité ..__, puis procédez comme suit dans AppDelegate:

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's value first and assign your rootViewController
   if let window = self.window {
      window.rootViewController = rootController
   }

   return true
}
44
fruechtemuesli

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
  }
15
A.G

Si vous n'utilisez pas de scénarimage, vous devez faire certaines choses. À l'intérieur de AppDelegate à l'intérieur de l'application de fonction.

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
}
12
   if let tabBarController = self.window!.rootViewController as? UITabBarController
    {
        tabBarController.selectedIndex = 0
    }
0
Thiago Arreguy