0

我有一个设置视图,可让您开始新游戏或继续进行中的游戏。我试图仅在游戏正在进行时显示“继续游戏”按钮,但我无法让它工作。一旦您开始新游戏,然后返回设置页面,这些按钮将不再起作用。

是因为在视图重新加载期间状态正在改变吗?如果是这样,如何在不导致视图自动重新加载的情况下更改状态?

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
        }
    }
}
4

0 回答 0