How to reuse an alert dialog inside a SwiftUI View?

Viewed 156

I want to be able to show an error popup ( Alert ) in all my views whenever some error condition occurs.

On the "logic" side this can be done by implementing a ViewModel base class containing:

    @Published var showError: Bool = false
    @Published var errorMessage: String = ""

Any subclass can then set those values if an error occured.

The problem however is on the View side. I would need to add the following code to every View that can show an alert:

        .alert(isPresented: $viewModel.showError) {
                return Alert(title: Text("error"), message: Text(viewModel.errorMessage), dismissButton: .default(Text("ok")))
        }

Is there a way to not have to copy paste this everywhere? Otherwise if I want to change the Alert behaviour I would need to adapt it all over my codebase.

0 Answers
Related