在 SwiftUI 文本中显示已发布的整数

Displaying a published integer in SwiftUI Text

我对 SwiftUI 还很陌生,运行 遇到了以下问题:

我有一个包含一些整数值的模型,如下所示:

class Game: ObservableObject {

    @Published var ownScore:Int = 0
    @Published var opponentScore:Int = 0

    ... some methods
}

我还需要一个视图来显示这些分数,并在任何这些值发生变化时得到更新。 我需要一些与此类似的东西,但是,这不起作用,因为这些值是已发布的整数。

struct ScoreView: View {
    @EnvironmentObject var game: Game
    @State var displayOpponent: Bool

    var body: some View {
        VStack {
            if displayOpponent {
                Text("Opponent Score")
                Text("Score: \(game.$opponentScore)")
            } else {
                Text("Your Score")
                Text("Score: \(game.$ownScore)")
            }

        }
    }
}

关于如何正确实施这个的任何想法?

仅在文本中使用属性,发布时它们将自动更新

struct ScoreView: View {
    @EnvironmentObject var game: Game
    @State var displayOpponent: Bool

    var body: some View {
        VStack {
            if displayOpponent {
                Text("Opponent Score")
                Text("Score: \(game.opponentScore)")   // no $ 
            } else {
                Text("Your Score")
                Text("Score: \(game.ownScore)")        // no $
            }

        }
    }
}

你的 Game 对象需要被实例化为 @ObservedObject 而不是 @EnvironmentObject 除非你将它注入到代码中未显示的环境中,所以......

class Game: ObservableObject {

    @Published var ownScore:Int = 0
    @Published var opponentScore:Int = 0
}

struct ContentView: View {
    @ObservedObject var game = Game()
    @State var displayOpponent: Bool = true

    var body: some View {
        VStack {
            if displayOpponent {
                Text("Opponent Score")
                Text("Score: \(game.opponentScore)")
            } else {
                Text("Your Score")
                Text("Score: \(game.ownScore)")
            }
        }
    }
}

...会起作用。此外,您只是提供已发布变量的值,因此不需要 $