In SwiftUI framework you have several options for implementing Alert, for example:
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
Here is a simple example of using the first option:
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
}
}
with code above you'll achieve this:
