やりたいこと
初回起動と2回目以降で、表示させるStoryboardを分岐させる。
開発の途中で「初回画面を追加したい」となり、起動時に遷移させる画面を変更するのに割と手こずってしまいました。
環境
Swift5, Xcode12
やり方
メインとなる画面をMain.Storyboardで作っていたので、そこにViewControllerを追加するのが一番シンプルなやり方のようです。
作成した両方のStoryboardにidentifierを設定します。
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を追加するか、メインの画面への遷移処理を書けば完了です。