swiftui alert in swift

To display an alert in SwiftUI, you can use the alert modifier along with the Alert struct. Here's an example of how to create and display an alert in SwiftUI:

main.swift
struct ContentView: View {
    @State private var showingAlert = false
    
    var body: some View {
        VStack {
            Button("Show Alert") {
                showingAlert = true
            }
        }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Alert"), message: Text("This is an alert"), dismissButton: .default(Text("OK")))
        }
    }
}
389 chars
15 lines

In the example above, we have a button that sets the showingAlert state variable to true when tapped. This triggers the alert modifier, which presents the alert when showingAlert is true.

The Alert struct creates an alert with the specified title, message, and dismiss button. You can customize the alert further by adding more buttons or actions.

Note that alert is a modifier that needs to be attached to a view, which is why we wrap the button and the alert modifier in a VStack in this example.

Hope this helps!

related categories

gistlibby LogSnag