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
    Alert(
        title: Text(self.alertTitle),
        message: Text(self.alertMessage),
        dismissButton: .default(Text("OK")) {

            // this will be called when the dismiss button is clicked
            print("dismissed")
        }
    )
})

Leave a Reply

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