В инфраструктуре 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
}
}
с кодом выше вы достигнете этого:
