The Slider
form control in SwiftUI allows us to create a bar that the user can swipe left or right to decrease or increase its value.
To initialize a Slider
, we need to set three parameters: value
, in
, and step
:
@State private var age: Double = 0
//...
Slider(value: $age, in: 0...100, step: 1)
The in
parameter determines the minimum and maximum values allowed for the Slider
.
The step
parameter indicates the increment value. In this example, the Slider
will increase or decrease the value by 1. You can adjust the step to any value such as 10 or 0.2.
As the Slider
takes a Double
value, it incrementally adjusts the decimals by default.
Here’s an example implementation:
struct ContentView: View {
@State private var age: Double = 0
var body: some View {
Form {
Slider(value: $age, in: 0...100, step: 1)
Text("\(age)")
}
}
}
In the example above, I included a Text
view to display the value of age
.
Since the age
variable is of type Double
, it may display multiple decimals.
Formatting the decimal display will be covered in another post.