I am fairly new to SwiftUI and ran into the following problem:
I have a model that contains some integer values like so:
class Game: ObservableObject {
@Published var ownScore:Int = 0
@Published var opponentScore:Int = 0
... some methods
}
I also need a view to display these scores and get updated whenever any of these values change. I would need something along the lines of this, however, this doesn't work since the values are published integers.
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)")
}
}
}
}
Any ideas on how to implement this correctly?
Use in Text just properties, on published they will be updated automatically
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 $
}
}
}
}