In this tutorial, I am going to show you how to increase the value of a state variable every time tapping a button. Actually, I am going to perform the increment of a state variable by 1 every time the SwiftUI button will be pressed.
Let’s first create our state variable:
@State private var myInteger = 0
Now create our button and in the curly brackets, perform the increment operation of our state variable myInteger
:
Button("Tap Me") {
myInteger += 1
}
Now we have created our button. Inside the button action, you can notice the code myInteger += 1
which is responsible for increasing our state variable myInteger by 1 every time we press the button.
To verify the value of the variable myInteger
, let’s create a Text view:
Text("Volume is \(myInteger)")
Complete and final code
Below is our complete and final code for increasing our state variable value by 1 each time tapping the SwiftUI button:
import SwiftUI
struct ContentView: View {
@State private var myInteger = 0
var body: some View {
Button("Tap Me") {
// Increase by 1
myInteger += 1
}
// Print the live value of myInteger
Text("Volume is \(myInteger)")
}
}
Now you can run the above SwiftUI code. if everything goes right, you can see when the user tap the button, the value shown in the Text view increases by 1. If you tap or click the button 4 times, the. value becomes 4.
Below is given how it will look like: