Intro
Right now, the cat age slider is constant at 100 and not interactive. Use SwiftUI’s State and Binding to make it dynamic and display the selected age as well.
Step 1: Adding the State Variable
Inside the ContentView struct, before the body, add this code:
@State private var selectedAge: Double = 100
-
Why @State? You mark this variable with
@Statebecause it’s a value that changes as the user interacts with the slider.@Statetells SwiftUI to watch this variable and update any view using it whenever it changes.
Step 2: Connecting to the Slider
Find the slider code and update this part: value: .constant(100).
Slider(value: $selectedAge, in: 0...255)
-
The ‘$’ is Key: The dollar sign in front of
selectedAgecreates a Binding connection between the slider and the State variable created in Step 1.
Step 3: Displaying the Age
Modify the text view that currently says ‘100’. Update the code to the following:
Text(selectedAge, format: .number.precision(.fractionLength(0)))
The code might look complex, but it simply takes the selectedAge value and formats it as a whole number to display.
Testing the Changes
Now, run your app preview. Notice how the slider starts at 100, and the text display matches! Try moving the slider. See how the age updates instantly? That’s the power of State and Binding working together!
Outro
You’ve merely scratched the surface of State and Binding. Think of them as your building blocks for crafting dynamic and interactive user experiences in SwiftUI. Keep learning, and you’ll be amazed at what you can create!