Environmentobject Swiftui

[Solved] Environmentobject Swiftui | Swift - Code Explorer | yomemimo.com
Question : environmentobject swiftui

Answered by : tony-sacco

// Our observable object class
class GameSettings: ObservableObject { @Published var score = 0
}
// A view that expects to find a GameSettings object
// in the environment, and shows its score.
struct ScoreView: View { @EnvironmentObject var settings: GameSettings var body: some View { Text("Score: \(settings.score)") }
}
// A view that creates the GameSettings object,
// and places it into the environment for the
// navigation view.
struct ContentView: View { @StateObject var settings = GameSettings() var body: some View { NavigationView { VStack { // A button that writes to the environment settings Button("Increase Score") { settings.score += 1 } NavigationLink(destination: ScoreView()) { Text("Show Detail View") } } .frame(height: 200) } .environmentObject(settings) }
}

Source : https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views | Last Update : Fri, 22 Jul 22

Answers related to environmentobject swiftui

Code Explorer Popular Question For Swift