Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Putting multiple BindableObjects into Environment

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.

like image 698
ideveloper Avatar asked Jun 21 '19 08:06

ideveloper


People also ask

Can you have multiple environment objects SwiftUI?

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.

When should you assign a value to an @EnvironmentObject property?

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.

What is environment variable SwiftUI?

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.


1 Answers

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) 
like image 138
Martin R Avatar answered Oct 06 '22 05:10

Martin R