【发布时间】:2021-03-31 01:25:16
【问题描述】:
以下警报中的所需操作(在 SwiftUI 视图中)仅在第二次点击主按钮(“是”)后(在警报的第二次出现时)运行:
.alert(isPresented: $viewModel.showingAlert) {
Alert(
title: Text("Confirm your Selection"),
message: Text("Are you sure?"),
primaryButton: .default (Text("Yes")) {
handleGameOver()
},
secondaryButton: .destructive (
Text("No (try again)"))
)
}
如下所示,handleGameOver() 更新 viewModel 中的两个布尔值,由 SKScene“观察到”,其中“showingSolution == true”将 childNode 添加到场景中。
func handleGameOver() {
viewModel.showingSolution = true
viewModel.respondToTap = false
gameOver = true
}
供进一步参考...
我是这样设置的:
GameViewModel:
final class GameViewModel: ObservableObject {
@Published var showingAlert = false
@Published var tapOnTarget = false
@Published var respondToTap = true
@Published var showingSolution = false
}
在 SwiftUI 视图中:
struct GameView: View {
@ObservedObject var viewModel: GameViewModel
@Binding var showingGameScene : Bool
@Binding var gameOver: Bool
var scene: SKScene {
let scene = GameScene()
scene.size = CGSize(width: 400, height: 300)
scene.scaleMode = .aspectFit
scene.backgroundColor = UIColor(.clear)
scene.viewModel = viewModel
return scene
}
var body: some View { ...
SpriteView(scene: scene)
...
最后,在 SKScene 中:
class GameScene: SKScene {
var viewModel: GameViewModel?
...
在“touchesBegan”中使用“viewModel?.showingAlert = true”将“showingAlert”设置为 true。
我不能离开,因为第二次尝试就可以了。但显然这还不够好。 我做错了什么??????
【问题讨论】:
-
您的问题非常模糊(实际上我在这里什至看不到问题,问题是什么?)。您提到了一些值(
childNode、touchesBegan等),但不清楚您如何或在何处使用它们。请提供一个最低限度的可重现代码,我们可以尝试自己重现。也请澄清您的问题。 -
抱歉含糊不清。我认为标题虽然含蓄地表明了一个需要解决的问题。事实上,我认为我已经提供了足够的背景信息。 (生活和学习!)我以后会更加小心。无论如何,您的评论提示我仔细研究一下,我能够让事情按应有的方式工作。
标签: swiftui sprite-kit alert