Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Present a Confirmation Dialog in SwiftUI
Written by Team Kodeco

Sometimes in your app, you may need to seek user confirmation before performing certain actions. In such scenarios, SwiftUI provides the confirmationDialog view modifier. This view modifier presents a confirmation dialog to the user when a given condition is met.

The title parameter accepts a string used as the title of the dialog. The isPresented parameter is a binding to a Boolean that determines whether to present the dialog. The titleVisibility parameter determines the visibility of the dialog’s title and the actions parameter defines the actions available in the dialog.

Consider the following example:

struct ContentView: View {
  @State private var isShowingDialog = false
  var body: some View {
    Button("Empty Trash") {
      isShowingDialog = true
    }
    .confirmationDialog(
      "Are you sure you want to empty the trash?",
      isPresented: $isShowingDialog,
      titleVisibility: .visible
    ) {
      Button("Empty Trash", role: .destructive) {
        // Handle empty trash action.
      }
      Button("Cancel", role: .cancel) {
        isShowingDialog = false
      }
    }
  }
}

Tap Empty Trash and your preview should look like this:

A confirmation dialog in SwiftUI.
A confirmation dialog in SwiftUI.

In this example, tapping the Empty Trash button sets the isShowingDialog state to true, which in turn presents the confirmation dialog. The dialog includes two actions — one for confirming the action and another for cancelling it. Normally SwiftUI automatically decides whether to display the title or not, but here you override that behavior to always display it.

And that’s it! With this knowledge, you can now present a confirmation dialog in SwiftUI. Happy coding!

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.