简体   繁体   中英

How to create single EnvironmentObject instance in SwiftUI

I usually create EnvironmentObject like this

    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?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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