Show an alert with callback Swift UI
To show an alert with callback in Swift UI, you need 3 things:
- A boolean state variable that tells when to show the alert message.
- A string state variable that tells the title of the alert.
- 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:
1 2 3 | @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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // 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" ) } ) }) |