Programmatically set the initial view controller using Storyboards

前端 未结 22 2222
感情败类
感情败类 2020-11-22 15:00

How do I programmatically set the InitialViewController for a Storyboard? I want to open my storyboard to a different view depending on some condition which may

22条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 15:21

    Another solution with using Swift 3 and Swift 4 with avoiding force casting is like this

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        guard let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewController") as? YourViewController else {
            return false
        }
        self.window?.rootViewController = viewController
        self.window?.makeKeyAndVisible()
        return true
    }
    

    And below is using with UINavigationController

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        guard let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewController") as? YourViewController else {
            return false
        }
        let navigationController = UINavigationController(rootViewController: viewController)
        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()
        return true
    }
    

提交回复
热议问题