Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create an Alert in SwiftUI
Written by Team Kodeco

Sometimes in your app, you may want to alert the user about something important. SwiftUI provides an easy way to display alerts using the alert modifier.

This function presents an alert with a title, message and action buttons when a specified condition is true. This condition is usually a @State Boolean variable that controls whether the alert should be shown or not.

Here is a simple example:

struct ContentView: View {
  @State private var showAlert = false

  var body: some View {
    Button("Show Alert") {
      showAlert = true
    }
    .alert(
      "Important Message",
      isPresented: $showAlert,
      actions: {
        Button("OK") {
          // Handle the acknowledgement.
          showAlert = false
        }
      },
      message: {
        Text("This is an important alert message.")
      }
    )
  }
}

Tap Show Alert and your preview should look like this:

An alert in SwiftUI.
An alert in SwiftUI.

In this example, tapping the Show Alert button sets the showAlert state to true, which triggers the alert presentation. The alert contains an “OK” button, which, when pressed, sets showAlert back to false to dismiss the alert and a message that says “This is an important alert message.”

The title of the alert is set as “Important Message”, and it’s defined directly in the alert modifier.

The alert function is a powerful tool that allows you to display important messages to the user in a concise and user-friendly manner.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.