What's the purpose of .environmentObject() view operator vs @EnvironmentObject?

拈花ヽ惹草 提交于 2021-01-28 02:07:38

问题


I'm attempting to crawl out of the proverbial Neophyte abyss here.

I'm beginning to grasp the use of @EnvironmentObject till I notice the .environmentObject() view operator in the docs.

Here's my code:

import SwiftUI

struct SecondarySwiftUI: View {
    @EnvironmentObject var settings: Settings

    var body: some View {
        ZStack {
            Color.red
            Text("Chosen One: \(settings.pickerSelection.name)")
        }.environmentObject(settings) //...doesn't appear to be of use.
    }

    func doSomething() {}
}

I tried to replace the use of the @EnvironmentObject with the .environmentObject() operator on the view.
I got a compile error for missing 'settings' def.

However, the code runs okay without the .environmentObject operator.

So my question, why have the .environmentObject operator?

Does the .environmentObject() instantiates an environmentObject versus the @environmentObject accesses the instantiated object?


回答1:


Here is demo code to show variants of EnvironmentObject & .environmentObject usage (with comments inline):

struct RootView_Previews: PreviewProvider {
    static var previews: some View {
        RootView().environmentObject(Settings()) // environment object injection
    }
}

class Settings: ObservableObject {
    @Published var foo = "Foo"
}

struct RootView: View {
    @EnvironmentObject var settings: Settings // declaration for request of environment object

    @State private var showingSheet = false
    var body: some View {
        VStack {
            View1() // environment object injected implicitly as it is subview
            .sheet(isPresented: $showingSheet) {
                View2() // sheet is different view hierarchy, so explicit injection below is a must
                    .environmentObject(self.settings) // !! comment this out and see run-time exception
            }
            Divider()
            Button("Show View2") {
                self.showingSheet.toggle()
            }
        }
    }
}

struct View1: View {
    @EnvironmentObject var settings: Settings // declaration for request of environment object
    var body: some View {
        Text("View1: \(settings.foo)")
    }
}

struct View2: View {
    @EnvironmentObject var settings: Settings // declaration for request of environment object
    var body: some View {
        Text("View2: \(settings.foo)")
    }
}

So, in your code ZStack does not declare needs of environment object, so no use of .environmentObject modifier.



来源:https://stackoverflow.com/questions/59654734/whats-the-purpose-of-environmentobject-view-operator-vs-environmentobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!