我正在尝试在调用gameOver()
时添加警报。 “'警报'初始化程序的结果未使用”。如何初始化我创建的警报?
func gameOver() {
round = 0
score = 0
self.changeTarget()
}
解决方案尝试:
func gameOver() {
round = 0
score = 0
self.changeTarget()
Alert(title: Text("Game Over"),
message: Text("Thanks for playing"),
dismissButton: Alert.Button.default( Text("Play Again")))
}
答案 0 :(得分:2)
在SwiftUI框架中,您可以使用多种选项来实现Alert
,例如:
func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> some View where Item : Identifiable
func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> some View where Item : Identifiable
以下是使用第一个选项的简单示例:
struct GameOverAlert: View {
@State private var round = 0
@State private var score = 0
@State private var restartGame = false // variable for showing alert
var body: some View {
VStack {
Text("round: \(round)")
Text("score: \(score)")
HStack { // used this style just for brevity
Button(action: { self.score += 1 }) { Text("add score") }
Button(action: { self.gameOver() }) { Text("over game") }
}
Spacer() // only for presenting result
}
.alert(isPresented: $restartGame) {
Alert(title: Text("Your score is \(score)"), dismissButton: .default(Text("Play again")) {
self.playAgain()
})
}
}
// described logic here, but it should be in some ViewModel, etc
private func gameOver() {
restartGame = true
}
private func playAgain() {
score = 0
round = 0
}
}
使用上面的代码,您将实现以下目标:
答案 1 :(得分:0)
这最终显示了游戏警告。
.alert(isPresented: $alertIsVisible) { () -> Alert in
let roundedValue = sliderValueRounded()
if self.round == 5 {
return Alert(title: Text("Game Over"), message: Text("Your score was \(score)."), dismissButton: .default(Text("Play Again")) {
self.startOver()
})
} else {
return Alert(title: Text(alertTitle()), message: Text("The slider's value is \(roundedValue). \n" + "You scored \(pointsForCurrentRound()) points!"), dismissButton: .default(Text("Play Again")){
self.changeTarget()
self.round += 1
})}
}