首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.environmentObject()视图操作符vs @EnvironmentObject的目的是什么?

.environmentObject()视图操作符vs @EnvironmentObject的目的是什么?
EN

Stack Overflow用户
提问于 2020-01-08 22:33:13
回答 1查看 238关注 0票数 2

我想爬出这俗话说的新手深渊。

直到我注意到文档中的.environmentObject()视图操作符,我才开始掌握@EnvironmentObject的用法。

这是我的密码:

代码语言:javascript
复制
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对象访问实例化对象?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-09 06:10:37

下面是演示代码,用于显示EnvironmentObject & .environmentObject用法的变体(带有内联注释):

代码语言:javascript
复制
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修饰符。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59654734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档