SwiftUI: Putting multiple BindableObjects into Env

2020-07-02 04:09发布

问题:

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.

回答1:

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)


回答2:

According to the Apple Official guide I'm guessing if each view just has one environmentObject then doing that would be fine. When there happened to be more than one, I'm not sure how the object are referenced.