environmentobject swiftui in swift

EnvironmentObject is a way to share data between views in SwiftUI. To use it, you need to first create a reference to the object you want to share and then pass that reference to the views that need it.

Here is an example:

main.swift
class MyModel: ObservableObject {
    @Published var someProperty: String = "Hello, World!"
}

struct ContentView: View {
    @EnvironmentObject var myModel: MyModel
    
    var body: some View {
        // Use myModel.someProperty in your view
        Text(myModel.someProperty)
    }
}

// In your SceneDelegate.swift or App.swift
let myModel = MyModel()

WindowGroup {
    ContentView()
        .environmentObject(myModel)
}
429 chars
21 lines

In the example above, we first create a MyModel object which conforms to ObservableObject protocol. We then pass this object to ContentView using the environmentObject method. Finally, ContentView can access the myModel object by declaring @EnvironmentObject var myModel: MyModel.

related categories

gistlibby LogSnag