how to display a dialog in swiftui

Asked on 08/05/2024

1 search

To display a dialog in SwiftUI, you can use the alert or sheet modifiers, depending on the type of dialog you want to present. Here are some examples:

Using alert

The alert modifier is used to present an alert dialog with a title, message, and buttons.

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

    var body: some View {
        Button("Show Alert") {
            showAlert = true
        }
        .alert("Alert Title", isPresented: $showAlert) {
            Button("OK", role: .cancel) { }
        } message: {
            Text("This is an alert message.")
        }
    }
}

Using sheet

The sheet modifier is used to present a modal view.

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

    var body: some View {
        Button("Show Sheet") {
            showSheet = true
        }
        .sheet(isPresented: $showSheet) {
            SheetView()
        }
    }
}

struct SheetView: View {
    var body: some View {
        Text("This is a sheet.")
    }
}

Using confirmationDialog

For more complex dialogs, you can use confirmationDialog.

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

    var body: some View {
        Button("Show Dialog") {
            showDialog = true
        }
        .confirmationDialog("Dialog Title", isPresented: $showDialog) {
            Button("Option 1") { }
            Button("Option 2") { }
            Button("Cancel", role: .cancel) { }
        } message: {
            Text("This is a confirmation dialog.")
        }
    }
}

For more advanced usage and examples, you can refer to the session What’s new in SwiftUI from WWDC 2024.