SwiftUI: Using the Button View to Update App State
The Button
view in SwiftUI allows you to create interactive button elements in your app. There are two ways to declare a Button
:
Button with a label:
1
2
3Button("Button label") {
// Action to perform when button is tapped
}Button with a closure label:
1
2
3
4
5
6Button {
// Action to perform when button is tapped
} label: {
// Something else as the label, e.g., an image
Text("Button label")
}
The second way is commonly used when the button has a label other than plain text, such as an image.
Let’s use the first way to create a Button
in a SwiftUI app:
1 | struct ContentView: View { |
In the app, you will see a blue text that can be tapped to trigger the action.
To print something to the debugging console when the button is tapped, you can modify the code as follows:
1 | struct ContentView: View { |
Please note that this will work only when you run the app, not in the Xcode preview.
Now let’s add another step to the app. We’ll print the value of a property inside the button label:
1 | struct ContentView: View { |
To update the value of the count
property when the button is tapped, we can modify the code as follows:
1 | struct ContentView: View { |
However, you may encounter a compilation error: “Left side of mutating operator isn’t mutable: ‘self’ is immutable.” To fix this, you need to use the @State
property wrapper before declaring the property:
1 | struct ContentView: View { |
Now, when the label is clicked, the count
property value will increment.
Please note that the counter will reset to 0 each time the app is run because we are not persisting the state. We’ll cover that later.
Tags: SwiftUI, Button view, app state, @State, property wrapper