Alert in SwiftUI

In Xcode 15, we can display an alert using the .alert modifier.

Take a look at the code:

struct ContentView: View {
    @State var showAlert = false
    
    var body: some View {
        VStack {
            Button("Show Alert") {
                showAlert = true
            }
        }.alert("Important message", isPresented: $showAlert) {
            Button("OK", role: .cancel) {
                // Your action
            }
        }
        .padding()
    }
}

The role of the button can be:

  • .cancel
  • .destructive
struct ContentView: View {
    @State var showAlert = false
    
    var body: some View {
        VStack {
            Button("Show Alert") {
                showAlert = true
            }
        }.alert("Important message", isPresented: $showAlert) {
            Button("Delete", role: .destructive) {
                
            }
        }
        .padding()
    }
}

Note that using a button with .destructive is also added the default cancel button.

share this post with friends

Picture of Nicola De filippo

Nicola De filippo

I'm a software engineer who adds to the passion for technologies the wisdom and the experience without losing the wonder for the world. I love to create new projects and to help people and teams to improve

Leave a comment

Your email address will not be published. Required fields are marked *

Who I am

I'm a software engineer who adds to the passion for technologies the wisdom and the experience without losing the wonder for the world. I love to create new projects and to help people and teams to improve.

Follow Me Here

Get The Latest Updates

Periodically receive my super contents on coding and programming

join the family;)

Recent Posts