Structure¶
Alert¶
A representation for an alert presentation.¶
Declaration¶
struct Alert
Overview¶
An Alert is a modal-like presentation which contains a title, message, and between one and two action buttons. Alerts often convey important information about the state of the app and typically request feedback from the user. While the styling of alerts is semi-fixed, there are three available styles for the buttons to choose from: default(_:action:), destructive(_:action:), and cancel(_:action:). To actually present an alert, see alert(isPresented:content:).
An alert can be created with one of two initializers, depending on if one button or two is required. For example, to create an Alert with one button:
struct ExampleAlertView: View {
@State private var showAlert = false
var body: some View {
Button("Tap to view alert") {
showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(
title: Text("An important title!"),
message: Text("A message that adds additional context on the alert.")
)
}
}
}

If the dismissButton value is left unspecified (as it was in this example), it will default to a dismiss button with the text "Ok".
In order to customize the type of button (or to create an alert with two buttons), create a new Button instance and pass it in as a part of the initializer. For example, to make an alert with a cancel and destructive button:
struct ExampleAlertView: View {
@State private var showAlert = false
var body: some View {
Button("Tap to view alert") {
showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(
title: Text("Are you sure?"),
message: Text("The following action will delete everything. Please confirm."),
primaryButton: Alert.Button.destructive(Text("Delete")),
secondaryButton: Alert.Button.cancel(Text("No, take me back!"))
)
}
}
}

For illustrative purposes, the alert button values used the expanded syntax in this example. It is also valid to use the shorthand syntax when declaring alert buttons: .default(_:action:), .cancel(_:), or .destructive(_:action:)
Notes:
- Stylistically, .default and .cancel alert button styles are nearly identical with the exception that .cancel has a bolded font weight.
- Alert is the equivalent to UIKit's UIAlertController.
- For information on the human interface guidelines for alerts, see: https://developer.apple.com/design/human-interface-guidelines/ios/views/alerts/
Availability¶
iOS 13.0+
macOS 10.15+
tvOS 13.0+
watchOS 6.0+
Topics¶
Initializer¶
init(title:message:dismissButton:) Creates an alert with one button.
init(title:message:primaryButton:secondaryButton:) Creates an alert with two buttons.