我想爬出这俗话说的新手深渊。
直到我注意到文档中的.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的用法。
我有一个编译错误,因为缺少‘设置’def。
但是,没有.environmentObject操作符,代码运行良好。
那么我的问题是,为什么有.environmentObject操作符?
.environmentObject()是实例化environmentObject,还是@environmentObject对象访问实例化对象?
发布于 2020-01-09 06:10:37
下面是演示代码,用于显示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修饰符。
https://stackoverflow.com/questions/59654734
复制相似问题