Showing alerts in Swiftui

Is there any way to show alerts in Swiftui without using the "toggle" and writing (.alert(isPresented:content:))?

Answered by mohammedshaheen00 in 712229022

You can use "Identifiable":

// 1

struct ErrorInfo: Identifiable {

var id: Int
let title: String
let description: String

}

struct ContentView: View {

// 2

@State private var error: ErrorInfo?


var body: some View {
    VStack {
        // 3
        Text(error?.description ?? "nil")

        // 4
        Button("Error 1") {
            error = ErrorInfo(id: 1, title: "Title 1", description: "Message 1")

        }
        Button("Error 2") {
            error = ErrorInfo(id: 2, title: "Title 2", description: "Message 2")

        }
        Button("Error 3") {
            error = ErrorInfo(id: 3, title: "Title 3", description: "Message 3")

        }
        Spacer()
    }
    .alert(item: $error, content: { error in // 5

        Alert(
            title: Text(error.title),
            message: Text(error.description)
        )
    })
    .padding()
}

}

What is your code ? What is the issue with toggle ?

A typical code is as follows (with 2 alerts to show the principle):

struct ContentView: View {
    @State private var showingAlert1 = false
    @State private var showingAlert2 = false

    var body: some View {
        VStack {
            Button("Show 1") {
                showingAlert1 = true
            }
            .alert(isPresented: $showingAlert1) {
                Alert(title: Text("One"), message: nil, dismissButton: .cancel())
            }

            Button("Show 2") {
                showingAlert2 = true
            }
            .alert(isPresented: $showingAlert2) {
                Alert(title: Text("Two"), message: nil, dismissButton: .cancel())
            }

        }
    }
}
Accepted Answer

You can use "Identifiable":

// 1

struct ErrorInfo: Identifiable {

var id: Int
let title: String
let description: String

}

struct ContentView: View {

// 2

@State private var error: ErrorInfo?


var body: some View {
    VStack {
        // 3
        Text(error?.description ?? "nil")

        // 4
        Button("Error 1") {
            error = ErrorInfo(id: 1, title: "Title 1", description: "Message 1")

        }
        Button("Error 2") {
            error = ErrorInfo(id: 2, title: "Title 2", description: "Message 2")

        }
        Button("Error 3") {
            error = ErrorInfo(id: 3, title: "Title 3", description: "Message 3")

        }
        Spacer()
    }
    .alert(item: $error, content: { error in // 5

        Alert(
            title: Text(error.title),
            message: Text(error.description)
        )
    })
    .padding()
}

}

Thanks for feedback.

take care that alert(item:content:) has been deprecated.

https://developer.apple.com/documentation/swiftui/menu/alert(item:content:)

Showing alerts in Swiftui
 
 
Q