Skip to content

How to Use SwiftUI's Slider View

SwiftUI, Slider View1 min read

Sliders are a common UI element that allow users to select a value from a range of values by dragging or tapping on a slider thumb. In iOS development, you can use the Slider view provided by SwiftUI to implement slider functionality in your app.

In this tutorial, we will learn how to use the Slider view in SwiftUI with some examples.

Creating a Basic Slider

To create a basic slider in SwiftUI, you can use the following code:

1import SwiftUI
3struct ContentView: View {
4 @State var value = 50.0
6 var body: some View {
7 VStack {
8 Text("Value: \(value)")
9 Slider(value: $value, in: 0...100, step: 1.0)
10 }
11 }

Here we define the ContentView struct that conforms to the View protocol. Within the body property, we create a VStack to stack our views vertically.

We then add a Text view to display the current value of the slider, and a Slider view where we set the value parameter to a @State variable named value. The in parameter specifies the range of values that the slider can take, and the step parameter sets the increment value for the slider.

Customizing the Slider Appearance

You can customize the appearance of the slider by modifying its track and thumb using the Slider view's minimumTrackTintColor, maximumTrackTintColor, and thumbTintColor parameters.

1Slider(value: $value, in: 0...100, step: 1.0)
2 .padding()
3 .accentColor(.red)
4 .background(Color.gray.opacity(0.5))
5 .cornerRadius(10)

Here, we add some modifiers to the Slider view. We add padding to give it some spacing, set the accent color to red, set a gray background, and round the corners with a corner radius of 10.

Using a Slider to Control a View

You can also use a slider to control other views in your app by binding the slider value to a property of another view. For example, you can use a slider to control the font size of a text view.

1struct ContentView: View {
2 @State var fontSize = 20.0
4 var body: some View {
5 VStack {
6 Text("Hello, SwiftUI!")
7 .font(.system(size: CGFloat(fontSize)))
8 Slider(value: $fontSize, in: 12...48, step: 1.0)
9 }
10 }

Here, we bind the Slider view's value parameter to a @State variable named fontSize. We then use this value to set the font size of the Text view using the font modifier.


In this tutorial, we learned how to use the Slider view in SwiftUI to enable users to select a value from a range of values in your iOS app. We covered creating a basic slider, customizing the slider appearance, and using a slider to control a view.

The Slider view is a powerful tool for adding interactivity to your SwiftUI apps, and we hope that these examples have given you a good starting point for using it in your own projects.