In SwiftUI
it is possible to use the environmentObject
method of the View object to put a single BindableObject
into the environment.
What if I want to put multiple BindableObjects
at the same time into the environment? I don't see any solution for this in the SwiftUI documentation. I don't want to have to pass the objects in the constructor.
Using multiple environment objectsYou can define as many environment objects as you like. The principle works precisely the same, as long as you provide an environment object through the view modifier for each requested environment object type.
Just like @ObservedObject , you never assign a value to an @EnvironmentObject property. Instead, it should be passed in from elsewhere, and ultimately you're probably going to want to use @StateObject to create it somewhere. However, unlike @ObservedObject we don't pass our objects into other views by hand.
Overview. SwiftUI exposes a collection of values to your app's views in an EnvironmentValues structure. To read a value from the structure, declare a property using the Environment property wrapper and specify the value's key path. For example, you can read the current locale: @Environment(\.locale) var locale: Locale.
The call to environmentObject()
returns a (modified) view, therefore you can chain the calls to put multiple objects into the environment. Example:
let rootView = ContentView() .environmentObject(firstBindable) .environmentObject(secondBindable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With