import SwiftUI
class Counter: ObservableObject {
@Published var count = 0
}
struct SharedCounterScreen: View {
@StateObject private var counter = Counter()
var body: some View {
VStack(spacing: 40) {
CounterView1()
CounterView2()
}
.environmentObject(counter)
.padding()
}
}
struct CounterView1: View {
@EnvironmentObject var counter: Counter
var body: some View {
VStack {
Text("Count: \(counter.count)")
.font(.title)
Button("Increment in View 1") {
counter.count += 1
}
.buttonStyle(.borderedProminent)
}
}
}
struct CounterView2: View {
@EnvironmentObject var counter: Counter
var body: some View {
VStack {
Text("Count: \(counter.count)")
.font(.title)
Button("Increment in View 2") {
counter.count += 1
}
.buttonStyle(.borderedProminent)
}
}
}
struct SharedCounterScreen_Previews: PreviewProvider {
static var previews: some View {
SharedCounterScreen()
}
}We created a Counter class that holds the shared count and marks it with @Published so views update automatically.
The main screen SharedCounterScreen creates a single Counter instance with @StateObject and passes it down using .environmentObject(counter).
Two child views CounterView1 and CounterView2 use @EnvironmentObject to access the shared counter. Each shows the current count and a button to increment it.
When either button is tapped, the shared count increases, and both views update instantly because they observe the same shared state.