Sometimes you need to inform or ask the user about something, instead of creating a new view you can show an alert.
First, you need to keep information if the alert is shown inside State property.
@State private var showAlert = false
Next, you need to allow the user to take some action to invoke alert, for example, Button. On click, you need to change that property to true.
Button(“Show alert”) {
showAlert = true
}
The last step is to use .alert on Button and pass $showAlert. Inside create Alert that will be shown to the user.
.alert(isPresented: $showAlert) {
Alert(title: Text(“Alert title”), message: Text(“Alert message”), dismissButton: .default(Text(“OK”)))
}
Alert has few possible options, so use that one you need.
On each button click, there will be alert because the showAlert is toggled. You can change it also in other places for example inside onAppear.
.onAppear(perform: {
showAlert = true
})