LoginSignup
1
1

More than 1 year has passed since last update.

起動画面のStoryboardを分岐させる

Last updated at Posted at 2021-06-23

やりたいこと

初回起動と2回目以降で、表示させるStoryboardを分岐させる。
開発の途中で「初回画面を追加したい」となり、起動時に遷移させる画面を変更するのに割と手こずってしまいました。

環境

Swift5, Xcode12

やり方

メインとなる画面をMain.Storyboardで作っていたので、そこにViewControllerを追加するのが一番シンプルなやり方のようです。

スクリーンショット 2021-06-23 22.45.32.png

作成した両方のStoryboardにidentifierを設定します。
スクリーンショット 2021-06-23 22.49.20.png

SceneDelegateにコードを加えます。

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }

        //以下を追加
        let window = UIWindow(windowScene: scene as! UIWindowScene)
        self.window = window
        window.makeKeyAndVisible()
        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        if lanchIsFirstTime() {
            logFirstLanch()
            let vc = storyboard.instantiateViewController(identifier: "初回起動で表示させたいViewのIdentifier")
            window.rootViewController = vc
        } else {
            let vc = storyboard.instantiateViewController(identifier: "2回目以降に表示させたいViewのIdentifier")
            window.rootViewController = vc
        }
}

//UserDefaultsをセット
func logFirstLanch() {
    return UserDefaults.standard.set(true, forKey: STORED_KEY)
}
func lanchIsFirstTime() -> Bool {
    return !UserDefaults.standard.bool(forKey: STORED_KEY)
}

あとは初回起動画面にsegueを追加するか、メインの画面への遷移処理を書けば完了です。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1