我对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)")
}
}
}
}
...会工作。另外,您只是呈现已发布变量的值,因此不需要$
。