2

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

我开始掌握 @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() {}
}

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

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

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

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

4

1 回答 1

3

这是演示代码,用于显示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)")
    }
}

所以,在你的代码中 ZStack 没有声明环境对象的需要,所以没有使用.environmentObject修饰符。

于 2020-01-09T06:10:37.070 回答