簡體   English   中英

如何在 SwiftUI 中創建單個 EnvironmentObject 實例

[英]How to create single EnvironmentObject instance in SwiftUI

我通常像這樣創建 EnvironmentObject

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

並將其用於大量視圖

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

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

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

是否有任何好的做法來創建 EnvironmentObject 的單個成員並通過應用程序使用它?

這是一次創建的演示 - 隨處使用

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