我如何以编程方式设置一个故事板的InitialViewController ?我想打开我的故事板到一个不同的视图这取决于不同的启动条件。


当前回答

我认为这是不可能的。 相反,你可以有一个初始控制器它有segue到不同的视图控制器。在启动时,您可以决定以编程方式执行哪个segue。

其他回答

Swift 4, Xcode 9

在AppDelegate.swift文件中

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let firstVC = storyboard.instantiateViewController(withIdentifier: "firstViewController") as! firstViewController
    self.window?.rootViewController = firstVC
}

选择要首先打开的视图控制器,然后转到属性检查器。 转到初始场景,检查初始视图控制器选项。

这是你的初始视图控制器在应用启动时首先打开。

在AppDelegate.swift中,你可以添加以下代码:

let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "YourViewController_StorboardID")
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()

当然,你需要实现你的逻辑,基于什么标准你将选择一个合适的视图控制器。

另外,不要忘记添加一个标识(select storyboard -> Controller Scene -> Show the identity inspector -> assign StorboardID)。

找到了简单的解决方案-不需要从故事板和编辑项目信息选项卡中删除“初始视图控制器检查”,并使用makeKeyAndVisible,只是放置

self.window.rootViewController = rootVC;

in

- (BOOL) application:didFinishLaunchingWithOptions:

Swift 3:更新到@victor-sigler的代码

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    // Assuming your storyboard is named "Main"
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    // Add code here (e.g. if/else) to determine which view controller class (chooseViewControllerA or chooseViewControllerB) and storyboard ID (chooseStoryboardA or chooseStoryboardB) to send the user to

    if(condition){
        let initialViewController: chooseViewControllerA = mainStoryboard.instantiateViewController(withIdentifier: "chooseStoryboardA") as! chooseViewControllerA
        self.window?.rootViewController = initialViewController
    )
    }else{
        let initialViewController: chooseViewControllerB = mainStoryboard.instantiateViewController(withIdentifier: "chooseStoryboardB") as! chooseViewControllerB
        self.window?.rootViewController = initialViewController
    )

    self.window?.makeKeyAndVisible(

    return true
}