/

SwiftUI: Using Alerts to Display Messages

SwiftUI: Using Alerts to Display Messages

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:

1
2
3
4
5
6
7
8
9
10
11
12
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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:

1
2
3
.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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.

Counter App Screenshots
Counter App Screenshots
Counter App Screenshots

tags: [“SwiftUI”, “alerts”, “debugging”, “user feedback”]