如果值没有更新,为什么警报会触发故障

  • 本文关键字:故障 更新 如果 swift swiftui
  • 更新时间 :
  • 英文 :


我有以下警报:

.alert(scoreTitle, isPresented: $showingScore) {
Button("Continue", action: askQuestion)
} message: {
Text("Your score is (totalCorrectAnswers)")
}
.alert("Game Over", isPresented: $showingGameOver) {
Button("Play Again", action: resetGame)
} message: {
Text("Your total score was (totalCorrectAnswers)")
}

注意它们是如何由showingScoreShowingGameOver触发的

当以下事件处理程序被称为时,警报开始发挥作用

func flagTapped(_ number: Int) {
if number == correctAnswer {
scoreTitle = "Correct!"
totalCorrectAnswers += 1

} else {
scoreTitle = "Wrong! That was the flag of (countries[number])"
totalCorrectAnswers += 0
}
showingScore.toggle()
attempts += 1

if attempts == maxAttempts {
showingGameOver.toggle()
}
}

正如您所看到的,首先检查答案,根据答案是正确的还是错误的,第一个警报中将显示不同的消息。如果我们达到了尝试次数的极限,紧接着就会出现另一个警报,并重置游戏。

我遇到的问题是,如果最后一次尝试不正确,警报就会出现故障。最初,我没有这行totalCorrectAnswers += 0,但我猜测(正确地(这可能是必要的,以便在右侧触发警报。我的猜测是,这是固定的,因为totalCorrectAnswers是一个状态属性,它会触发刷新,但它并不能真正解释为什么需要这样做。

使用元组变量和交错警报的方法是一种方法。

你需要震惊,因为你不能可靠地提出一个高于另一个的警报,比如得到错误的答案和同时结束游戏。

import SwiftUI
@available(iOS 15.0, *)
struct AlertSampleView: View {
//One variable controls the single alert
@State var alertVariable:(title:String,isPresented: Bool, actionTitle: String ,action: () -> Void,message: String) = ("",false,"OK",{},"")
//MARK: Sample variables based on provided code
@State var correctAnswer = 1
@State var totalCorrectAnswers = 1
@State var attempts = 1
@State var maxAttempts = 2
var body: some View {
Button("answer", action: {
//Mimic result
flagTapped(Int.random(in: 0...2))
})
//Single alert
.alert(alertVariable.title, isPresented: $alertVariable.isPresented, actions: {
Button(alertVariable.actionTitle, action: alertVariable.action)
}, message: {
Text(alertVariable.message)
})
}
func flagTapped(_ number: Int) {
if number == correctAnswer {
scheduleAlert(title: "Correct!")

totalCorrectAnswers += 1
attempts = 0

} else {
scheduleAlert(title: "Wrong! That was the flag of ...")
attempts += 1
}
if attempts == maxAttempts {
scheduleAlert(title: "Game Over")
}
}
//Staggers the presentation of the alerts
func scheduleAlert(title: String, count:Int = 0){
//Delay Alert if there is one on the screen
if alertVariable.isPresented{
//After 5 secondsish dismiss what is there
if count >= 25{
alertVariable.isPresented = false
}
//This delay leaves a little gap between alerts
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
scheduleAlert(title: title, count: count + 1)
}
}else{
alertVariable.title = title
alertVariable.isPresented = true
}
}
}
@available(iOS 15.0, *)
struct AlertSampleView_Previews: PreviewProvider {
static var previews: some View {
AlertSampleView()
}
}

最新更新