gpt4 book ai didi

swiftui - .environmentObject() View 运算符与 @EnvironmentObject 的目的是什么?

转载 作者:行者123 更新时间:2023-12-03 08:49:54 28 4
gpt4 key购买 nike

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

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

这是我的代码:

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() {}
}

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

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

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

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

最佳答案

这里是演示代码,显示 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 修饰符。

关于swiftui - .environmentObject() View 运算符与 @EnvironmentObject 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59654734/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com