🧩 SceneDelegate.swift とは?

SceneDelegate は iOS 13 以降に導入された、1つ1つのウィンドウ(シーン)を管理するためのクラスです。マルチウィンドウ対応や画面ごとの状態管理に利用されます。


…読み込み中…

📌 SceneDelegateの主な役割

🧱 基本構造

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との違い

iPadなどでマルチウィンドウを使うアプリでは、SceneDelegateが非常に重要です。

🛠 SwiftUIを使う場合

// SwiftUI AppテンプレートではSceneDelegateは不要になります
@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

UIKitと併用する場合のみSceneDelegateを明示的に使う必要があります。

📚 関連リンク