How to create alerts in SwiftUI
To display alerts in SwiftUI, you can use the alert(_:isPresented:presenting:actions:message:)
modifier. Let’s explore the parameters that this modifier takes:
title
: Defines the title of the alert.isPresented: Binding<Bool>
: Determines whether the alert should be shown or not. When the user interacts with any of the alert’s actions, the system changes this value tofalse
and hides the alert.@ViewBuilder actions: () -> A
: It’s aViewBuilder
that returns the actions that will be available in the alert.
To use this modifier, for example, first, we’ll create a variable called showAlert
.
@State private var showAlert = false
Then, we’ll add a button to our body
that changes the state of the showAlert
variable to true
when pressed.
struct ContentView: View {
@State private var showAlert = false
var body: some View {
Button {
showAlert = true
} label: {
Text("Show alert")
.font(.title)
}
}
}
Finally, we add the alert
modifier to our view as follows:
.alert("Displaying alert", isPresented: $showAlert) {
Button("Ok", role: .cancel) { }
Button("Edit") { }
}
You can add more than one button as actions in your alert:
.alert("Displaying alert", isPresented: $showAlert) {
Button("Delete", role: .destructive) { }
Button("Edit") { }
Button("Ok", role: .cancel) { }
}
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/como-crear-alertas-en-swiftui/