How to Handle Dismiss Actions in iOS SwiftUI Alert
Alerts are a staple in iOS apps, serving as a way to inform users or capture their decisions. While creating alerts in SwiftUI is straightforward, handling their dismiss actions might require a bit more attention.
In this blog post, we’ll explore how to execute specific actions when a SwiftUI alert is dismissed.
What is a SwiftUI Alert?
A SwiftUI Alert is a pop-up message that appears on the screen to notify users or capture their input. It usually contains a title, a message, and one or more buttons.
Basic Alert with Dismiss Action
Create State Variables
First, let’s create two state variables. One for controlling the alert’s visibility and another to hold some data.
@State private var showAlert = false
@State private var someData = ""
The showAlert
variable will control the alert’s visibility, while someData
will hold some data that we might change when the alert is dismissed.
Trigger the Alert
Create a button to trigger the alert.
Button("Show Alert") {
showAlert = true
}
This button sets showAlert
to true, which will trigger the alert to appear.
Display the Alert with Dismiss Action
Now, let’s display the alert and add a dismiss action.
.alert(isPresented: $showAlert) {
Alert(title: Text("Hello, SwiftUI!"),
dismissButton: .default(Text("OK"), action: {
someData = "Alert Dismissed"
}))
}
We use the .alert
modifier and bind it to showAlert
. When the “OK” button is tapped, the alert will dismiss, and the someData
variable will be updated to “Alert Dismissed”.
Complete Code
Following is the complete code.
import SwiftUI
struct ContentView: View {
@State private var showAlert = false
@State private var someData = ""
var body: some View {
Button("Show Alert") {
showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Hello, SwiftUI!"),
dismissButton: .default(Text("OK"), action: {
someData = "Alert Dismissed"
}))
}
}
}
Handling dismiss actions in SwiftUI alerts is not complicated but does require some understanding of state management. Whether you’re dealing with a simple alert or a more complex one with multiple buttons, SwiftUI provides the tools you need to capture and handle dismiss actions effectively.