Create a Slider in SwiftUI
Written by Team Kodeco
Sliders are a common UI element that allow users to select a value within a range by dragging a slider thumb. In SwiftUI, the Slider view provides a simple way to add this functionality to your app.
Here’s an example:
struct ContentView: View {
@State private var value: Double = 0.5
var body: some View {
VStack {
Slider(value: $value, in: 0...1)
Text("Value: \(value, specifier: "%.2f")")
}
}
}
Your preview should look like this:
In the code above, you create a VStack that contains a Slider and a Text view to display the current slider value. The slider’s value is bound to the value state variable using the $value syntax.
The Slider view takes two parameters: value and in. The value parameter is a binding to a double variable that represents the current value of the slider. The in parameter is a range that defines the minimum and maximum values of the slider.
The Text view displays the value variable using a string specifier to format the value with two decimal places.
Overall, using the Slider view to add slider functionality to your SwiftUI app is a straightforward process that can be customized with additional parameters to suit your specific needs.