Member-only story

SwiftUIT-5 (Important questions)

Questions:
1. I want to change value throughout the application, how to achieve it in swiftUI?

2. Key Difference Between @Environment and @EnvironmentObject

Q1. I want to change value throughout the application, how to achieve it in swiftUI?

The recommended approach for shared data across the app is to use a @StateObject in a parent view and inject it as an @EnvironmentObject for child views.

Steps:

  1. Create a Data Model:
import SwiftUI

class AppState: ObservableObject {
@Published var sharedValue: String = "Default Value"
}

2. Provide the AppState to the Environment:

@main
struct MyApp: App {
@StateObject private var appState = AppState()

var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appState)
}
}
}

3. Access and Modify the Value in Views:

  • Parent View:
struct ContentView: View {
@EnvironmentObject var appState: AppState

var body: some View {
VStack {
Text("Shared Value: \(appState.sharedValue)")
Button("Change Value") {
appState.sharedValue = "Updated Value"
}
ChildView() // Pass the environment to child views
}
}
}
  • Child View:
struct ChildView…

--

--

No responses yet