I have a setup view that lets you either start a new game or continue an ongoing game. I'm trying to show a "Continue Game" button only if the game is in progress but I can't get it to work. Once you start a new game and then go back to the setup page, the buttons no longer work.
Is it because the state is changing during view reloading? If so, how can you change state without causing an automatic reload of the view?
import SwiftUI
class Score: ObservableObject {
@Published var points = 0
func reset() {
points = 0
}
}
struct ContentView: View {
@ObservedObject var score = Score()
@State private var presentGameView = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: GameView(score: score), isActive: $presentGameView) {
EmptyView()
}
if score.points > 0 {
Button("Continue Game") {
self.presentGameView = true
}
}
Button("New Game") {
self.score.reset()
self.presentGameView = true
}
}
}
}
}
struct GameView: View {
var score: Score
var body: some View {
Button("Add Point to Score") {
self.score.points += 1
}
}
}