1

我对 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)")
            }

        }
    }
}

关于如何正确实现这一点的任何想法?

4

2 回答 2

2

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

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

        }
    }
}
于 2020-04-09T10:00:12.187 回答
0

您的Game对象需要实例化为@ObservedObjectnot an@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)")
            }
        }
    }
}

...会工作。此外,您只是显示已发布变量的值,因此 $不需要。

于 2020-04-09T10:00:43.353 回答