Home Using ConfirmationDialog Modifier to Show Multiple Options in SwiftUI
Post
Cancel

Using ConfirmationDialog Modifier to Show Multiple Options in SwiftUI

The confirmationDialog modifier in SwiftUI is a handy little modifier that allows us to present pop-up dialogs to confirm actions or decisions within our iOS apps. These dialogs are great for getting user confirmation before executing critical tasks, like deleting an item or making significant changes.

Ah, this is one of those modifiers I somehow missed! Silly me, assuming alert() was the only game in town. But of course, it makes perfect sense. Both alert() and confirmationDialog offer similar functionality to UIKit’s UIAlertController.

ConfirmationDialog in Action

To use confirmationDialog, we start by defining it with a title, message, and specify the action buttons. For example, we might set the title as "Confirmation" and the message as "Are you sure you want to delete this item?" Then, we can add buttons like "Delete" and "Cancel".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct DialogExample: View {
    @State private var showDialog = false
    
    var body: some View {
        Button("Delete Item") {
            showDialog = true
        }
        .confirmationDialog("Confirmation", isPresented: $showDialog) {
            Button("Archive Item") { }
                        
            Button("Bookmark Item") { }

            Button("Delete Item", role: .destructive) { }
            
            Button("Cancel", role: .cancel) { }
        } message: {
            Text("Are you sure you want to delete this item?")
        }
    }
}

Pretty straightforward, this article’s mainly a reminder for myself—gotta remember this modifier exist, tired of using alert() everywhere, ha! Alright, Bye for now!

This post is licensed under CC BY 4.0 by the author.