📌 SceneDelegateの主な役割
- UIWindowの生成と管理 - 概要
- シーン(画面)の表示・復帰・破棄の監視
- 状態復元(State Restoration)対応
- ユーザー切り替えやマルチウィンドウ操作の対応
🧱 基本構造
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let window = UIWindow(windowScene: windowScene)
window.rootViewController = YourRootViewController() // ここに初期画面を設定
self.window = window
window.makeKeyAndVisible()
}
func sceneDidBecomeActive(_ scene: UIScene) {
// シーンがアクティブになったとき
}
func sceneWillResignActive(_ scene: UIScene) {
// 一時的に非アクティブ
}
func sceneDidEnterBackground(_ scene: UIScene) {
// バックグラウンドに移行
}
func sceneWillEnterForeground(_ scene: UIScene) {
// フォアグラウンドに戻る前
}
func sceneDidDisconnect(_ scene: UIScene) {
// シーンが破棄される直前
}
}
🔍 AppDelegateとの違い
- AppDelegate:アプリ全体の初期化や通知、バックグラウンド処理など
- SceneDelegate:個別の画面・ウィンドウごとの状態管理(UIに特化)
iPadなどでマルチウィンドウを使うアプリでは、SceneDelegateが非常に重要です。
🛠 SwiftUIを使う場合
// SwiftUI AppテンプレートではSceneDelegateは不要になります
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
UIKitと併用する場合のみSceneDelegateを明示的に使う必要があります。