Alert messages are a useful way to provide feedback to users and aid in debugging applications. In SwiftUI, you can leverage the .alert()
modifier to display alerts based on certain conditions.
Let’s consider an example where we have a Button
with an associated counter:
import SwiftUI
struct ContentView: View {
@State var count = 0
var body: some View {
Button("Count: \(count)") {
self.count += 1
}
.font(.title)
}
}
Suppose we want to show an alert message when the count
reaches 10. To achieve this, we can introduce a boolean property showAlert
in the ContentView
and modify the tap action of the Button
as follows:
struct ContentView: View {
@State var count = 0
@State var showAlert = false
var body: some View {
Button("Count: \(count)") {
self.count += 1
if self.count == 10 {
showAlert = true
self.count = 0
}
}
.font(.title)
}
}
In this updated code, we set showAlert
to true and reset the count to 0 when it reaches 10.
Now, let’s add the .alert()
modifier to the Button
view to display the alert:
.alert(isPresented: $showAlert) {
Alert(title: Text("Great!"), message: Text("You reached 10"))
}
This alert will only be shown when the showAlert
property is true. Dismissing the alert automatically sets the showAlert
property to false.
Here’s the complete code:
struct ContentView: View {
@State var count = 0
@State var showAlert = false
var body: some View {
Button("Count: \(count)") {
self.count += 1
if self.count == 10 {
showAlert = true
self.count = 0
}
}
.font(.title)
.alert(isPresented: $showAlert) {
Alert(title: Text("Great!"), message: Text("You reached 10"))
}
}
}
Try running the app. The counter starts at 0, and clicking the button increments the counter. When the count reaches 10, the alert message is displayed. After dismissing the alert, the counter resets to 0.