如何使用Swift,iOS 7设置rootViewController

我想在应用程序委托中设置rootViewController ..

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { var rootView: MyRootViewController = MyRootViewController() //Code to set this viewController as the root view?? return true } 

你可以做这样的事情。

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { var rootView: MyRootViewController = MyRootViewController() if let window = self.window{ window.rootViewController = rootView } return true } 

如果您正在使用故事板,并且想要以编程方式设置rootViewController,请首先确保ViewController在Identity Inspector中具有Storyboard ID。 然后在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 } 

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 } 

为了让它显示有一些事情,如果你不使用故事板,你需要做的。 在函数应用程序里面的AppDelegate里面。

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