How to create alerts in SwiftUI

AsyncLearn
2 min readMar 25, 2024

--

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 to false and hides the alert.
  • @ViewBuilder actions: () -> A: It’s a ViewBuilder 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") { }
}
Example of an Alert in SwiftUI

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) { }
}
Example of an Alert with options in SwiftUI

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/

--

--

AsyncLearn

Stay up-to-date in the world of mobile applications with our specialised blog.