LoginSignup
0
0

More than 1 year has passed since last update.

AppDelegateで@EnvironmentObjectを使用する方法

Posted at

SceneDelegate.swiftに、ContentViewに渡すEnvironmentObjectを生成するコードを追加します。

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    var appState = AppState()
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // アプリケーションの初期化処理を行う
        let contentView = ContentView().environmentObject(appState)
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
}

ContentViewに、@EnvironmentObjectで参照するAppStateを指定します。

struct ContentView: View {
    @EnvironmentObject var appState: AppState

    var body: some View {
        // Viewの定義
    }
}

ContentViewをSceneDelegateから生成するとき、environmentObjectメソッドを使用して、appStateオブジェクトを渡します。

let contentView = ContentView().environmentObject(appState)

以上の手順で、AppDelegateで生成したappStateオブジェクトを、ContentViewの@EnvironmentObjectで参照できるようになります。@EnvironmentObjectを使用することで、複数のViewで同じオブジェクトを参照できるため、便利にアプリケーションの状態管理を行うことができます。

0
0
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
0
0