There are two components that are similar; both allow users to choose a value within a range. They are:
- Stepper
- Slider
Both share a definition that uses the same type of parameter.
Stepper
So, we can adjust the age by increasing or decreasing it using the buttons, with an initial value set to four.
struct ContentView: View {
@State var value: Int = 4
var body: some View {
VStack {
Stepper(value: $value, in: 1...100) {
Text("Age \(value)")
}
}
}
}
We can also set the value of the increase/decrease using the step:
struct ContentView: View {
@State var value: Int = 4
var body: some View {
VStack {
Stepper(value: $value, in: 1...100, step: 5) {
Text("Age \(value)")
}
}
}
}
If we use a Double for the value and range, we can also use a Double for the step.
Instead of text, we can also use a label:
Stepper(value: $value, in: 1...100, step: 5) {
Label("Age \(value)", systemImage: "calendar.and.person")
}
There is also a closure that communicates when the stepper is clicked: onEditingChanged.
struct ContentView: View {
@State var value: Int = 4
@State var editing = false
var body: some View {
VStack {
Stepper(value: $value, in: 1...100, step: 5, onEditingChanged: { edit in
editing = edit
}) {
Label("Age \(value)", systemImage: "calendar.and.person")
}
}.foregroundStyle((editing) ? .red: .green)
}
}
In this case, while clicking the stepper, the text and the icon change their color to red.
Slider
The slider, apart from its different look and interaction, has the same parameters as the stepper:
struct ContentView: View {
@State var value: Double = 4.0
@State var editing = false
var body: some View {
VStack {
Slider(value: $value, in: 0...100.0, step: 5.0, onEditingChanged: { edit in editing = edit})
Text("\(value)")
}.foregroundStyle((editing) ? .red: .green)
}
}
If we pass only the value as a parameter, the default values are: an interval of 0…1 and a step of 0.1.
I know that these components are not used often, but it is good to know how they work.
Leave a Reply