Show an alert with a callback - Swift UI

Show an alert with callback Swift UI


To show an alert with callback in Swift UI, you need 3 things:

  1. A boolean state variable that tells when to show the alert message.
  2. A string state variable that tells the title of the alert.
  3. A string state variable that tells the content of an alert message.

Video tutorial:

So let’s go ahead and create these 3 variables in your view:

@State var showAlert: Bool = false
@State var alertTitle: String = ""
@State var alertMessage: String = ""

When the variable becomes true, an alert will be displayed with a title and a message.

// main layout
VStack {

    // when clicked will show the alert
    Button(action: {
        // set title of alert
        self.alertTitle = "Error"

        // set message of alert
        self.alertMessage = "Please try again"
        // this line will actually show the alert
        self.showAlert = true
    }, label: {
        // text to show in button
        Text("Show alert")
    // bind showAlert here
}.alert(isPresented: $showAlert, content: {

    // alert dialog
        title: Text(self.alertTitle),
        message: Text(self.alertMessage),
        dismissButton: .default(Text("OK")) {

            // this will be called when the dismiss button is clicked

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post

Leave a Reply