我在 ContentView 页面上看不到 Text 对象的变化。但是,当我在带有打印的 .onReceive 中运行相同的代码时,我可以看到变化。这里有什么问题?
我想从不同的地方管理游戏的状态和从不同的地方运行游戏。我的逻辑错了吗?
枚举
enum GameSituation {
case play
}
游戏配置
class GameConfig: ObservableObject {
@Published var randomCellValue: Int = 0
@Published var timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()
func startGame() {
determineRandomCell()
}
func determineRandomCell() {
randomCellValue = Int.random(in: 0...11)
}
func playSound(soundfile: String, ofType: String) {
if let path = Bundle.main.path(forResource: soundfile, ofType: ofType){
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print("Error")
}
}
}
}
游戏情况
class GameSituations: ObservableObject {
@Published var gameConfig = GameConfig()
func gameSituation(gameSituation: GameSituation) {
switch gameSituation {
case .play:
gameConfig.startGame()
}
}
}
内容视图
struct ContentView: View {
@StateObject var gameSituation = GameSituations()
var body: some View {
Text("\(gameSituation.gameConfig.randomCellValue)")
.padding()
.onReceive(gameSituation.gameConfig.timer, perform: { _ in
gameSituation.gameSituation(gameSituation: .play)
print("random: \(gameSituation.gameConfig.randomCellValue)")
})
}
}