简体   繁体   English

如何在 SwiftUI 中创建单个 EnvironmentObject 实例

[英]How to create single EnvironmentObject instance in SwiftUI

I usually create EnvironmentObject like this我通常像这样创建 EnvironmentObject

    class UserSettings: ObservableObject {
        
        @Published var obsValue1 = false
        @Published var obsValue2 = true
    }
    
    

And use it into ton of views并将其用于大量视图

struct Example1: View {
    
    @EnvironmentObject var settings: UserSettings
    //...
}

struct Example3: View {
    
    @EnvironmentObject var settings: UserSettings
    //...
}

struct Example3: View {
    
    @EnvironmentObject var settings: UserSettings
    //...
}

Is there any good practice to create a single member of EnvironmentObject and use it through the app?是否有任何好的做法来创建 EnvironmentObject 的单个成员并通过应用程序使用它?

Here is a demo of once created - used everywhere这是一次创建的演示 - 随处使用

struct DemoView: View {
    var userSettings = UserSettings()   // one instance
    var body: some View {
        VStack {
            Text("Value: " + String(describing: userSettings.obsValue1))  // << usage
            Example2()
        }.environmentObject(userSettings) // << injected into all subviews !!
    }
}

struct Example1: View {
    // @EnvironmentObject var settings: UserSettings // not needed as not used
                                                   // passed below automatically
    var body: some View {
        VStack {
            Example2()
        }
    }
}

struct Example2: View {
    @EnvironmentObject var settings: UserSettings
    var body: some View {
        VStack {
            Text("Value2: " + String(describing: settings.obsValue1))  // << usage
            Example3()
        }
    }
}

struct Example3: View {
    @EnvironmentObject var settings: UserSettings
    var body: some View {
            Text("Value3: " + String(describing: settings.obsValue1))  // << usage
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM