はじめに
アプリの初期画面をwindow.rootViewControllerを用いて表示することは採用したアーキテクチャにもよると思いますが、よくあることかと思います。
ただし、プロジェクト作成時にLife CycleでSwiftUI Appを選択した場合に少し実装が必要だったため記しておきます。
実装
SwiftUI Appでプロジェクトを作成すると、以下のようなファイルが生成されます。
このままだとContentViewが初期表示画面になってしまいます。
例えばCoordinatorやRooterパターン等を利用したい場合はAppDelegateやSceneDelegateを経由したくなります。
import SwiftUI
@main
struct SampleApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
まず、AppDelegateとSceneDelegateをそれぞれ自分で作成します。
自作したSceneDelegateが呼び出されるような実装をAppDelegateにしていきます。
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = SampleViewController()
window.makeKeyAndVisible()
self.window = window
}
}
}
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
let config = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
config.delegateClass = SceneDelegate.self
return config
}
}
これであとは、AppDelegateが呼び出されるようにするだけです。
@UIApplicationDelegateAdaptorを利用します。
import SwiftUI
@main
struct SampleApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
}
}
}
これで、SceneDelegateで指定しているSampleViewControllerが表示されるようになります。
おわりに
そもそもSwiftUI Appを選択しなければ良い話ですが、参考になる方がいればいいなと思います。
単純に起動時に処理がしたいだけであればScenePhaseというものもあるようです。
https://developer.apple.com/documentation/swiftui/scenephase