How to remove alert view button in SwiftUI

296 Views Asked by At

I have scenario where I need to display an alert without any button. Is it possible to remove the buttons from the default Alert in SwiftUI?

I know how to create a custom view as Alert. But I would love to use the default one instead of creating a custom one.

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

    var body: some View {
        Button("Show Alert") {
            showingAlert = true
        }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
        }
    }
}

enter image description here

1

There are 1 best solutions below

0
Sweeper On

No, the alert view modifier cannot create alerts without any buttons. The descriptions of the initialisers for Alert are:

Creates an alert with one button.

Creates an alert with two buttons.

Creates a side by side button alert.

All of these create alerts with buttons.

Note that Alert is deprecated since iOS 16.4. Now you should use one of the new alert modifiers like this one.

However, the new alert modifiers cannot create alerts without buttons either. All of their documentation mentions that:

If no actions are present, the system includes a standard “OK” action.