@EnvironmentObject
declare an environment object
SwiftUI โฉ Data Flow โฉ @EnvironmentObject
The @EnvironmentObject
property wrapper is used to declare (in a subview) an environment object property provided by an ancester view.
// app
struct MyApp: App {
// โญ๏ธ 1. initialize a state object (as the app's model data)
@StateObject private var modelData = ModelData()
var body: some Scene {
WindowGroup {
RootView()
// โญ๏ธ 2. put the model object in the environment.
.environmentObject(modelData)
}
}
}
// assume Subview is a subview of RootView in the view hierarchy
struct Subview: View {
// โญ๏ธ 3. get the model object from environment.
@EnvironmentObject var modelData: ModelData
var body: some View { ... }
}
Be sure to set a corresponding model instance on an ancester view by calling its .environmentObject(_:) modifier.
Use ObservableObject to declare an observable object type.
Use @Published to declare published values in an observable object type.
Use @StateObject to initialize an observable object.
Use .environmentObject(_:) to put the model object in the environment.
Use
@EnvironmentObject
to declare an observable object property provided by an ancestor view.observer๏ผ any view or object that uses the observable object's data.
data model๏ผdata shared with any views in your app.
Last updated
Was this helpful?