I have a simple project as follows.
import SwiftUI
class GameSettings: ObservableObject {
@Published var score: Int = 100
}
struct ContentView: View {
@StateObject var settings = GameSettings()
var body: some View {
GeometryReader { geo in
ZStack {
HStack(spacing: 0.0) {
RightView().environmentObject(GameSettings())
.frame(width: geo.size.width / 2.0, height: geo.size.height)
Spacer()
}
VStack {
HStack {
Spacer()
Button {
print("\(settings.score)")
} label: {
Text("Print")
.font(.largeTitle)
}.padding(.trailing, 40.0)
}
Spacer()
}
}
}
}
}
struct RightView: View {
@EnvironmentObject var settings: GameSettings
var body: some View {
ZStack {
Color.red
Button {
settings.score += 100
} label: {
Text("Change")
.font(.largeTitle)
}
}.environmentObject(settings)
}
}
So the score is supposed to increase by 100 if I tap the button over the red area. And I want to print the latest value by tapping the Print button at the top-right corner. But it will remain at 100. What am I doing wrong? And can I achieve my goal without using an @ObservedObject variable? Thanks.