.environmentObject() 视图运算符与 @EnvironmentObject 的目的是什么?

Fre*_*Lee 2 swiftui swiftui-environment

我正试图从这里众所周知的新手深渊中爬出来。

我开始掌握 @EnvironmentObject 的使用,直到我注意到文档中的 .environmentObject() 视图运算符。

这是我的代码:

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() {}
}
Run Code Online (Sandbox Code Playgroud)

我尝试在视图上用 .environmentObject() 运算符替换 @EnvironmentObject 的使用。
我因缺少“设置”定义而出现编译错误。

但是,如果没有 .environmentObject 运算符,代码也可以正常运行。

所以我的问题是,为什么有 .environmentObject 运算符?

.environmentObject() 是否实例化环境对象,而 @environmentObject 是否访问实例化对象?

Asp*_*eri 5

这是演示代码,显示EnvironmentObject&.environmentObject用法的变体(内嵌注释):

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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,在您的代码中 ZStack 没有声明环境对象的需求,因此没有使用.environmentObject修饰符。