Slider is a user interface control which enables you to select a value from a specified linear range of values by using touch. Slider in SwiftUI is very similar to a UISlider in UIKit. This tutorial will teach you how to create and use a slider in SwiftUI. In order to read a value from a SwiftUI slider, you need to bind it to a state variable.

Create a slider and read the slider’s value

struct ContentView: View { @State var sliderValue: Double = 0 var body: some View { VStack { Slider (value: $sliderValue, in: 0 ... 20 ) Text ( "Current slider value: \(sliderValue, specifier: "%.2f") ") }. padding () } }

First, we defined a State variable called sliderValue which is being used by the slider to store its current value.

Then, we initialized the slider by passing a binding to sliderValue and specified a range of possible values of the slider.

Finally, we added a Text view to display the slider’s current value, rounded to two decimal places.

The result should look like this:

Slider in SwiftUI

Change slider’s step (increment) value

In the above example, the slider’s value is very precise and changes by a small fraction when you move it. In order to specify by how much do you want to update the slider’s value when you move it, use the step parameter:

Slider (value: $sliderValue, in: 0 ... 20 , step: 1 )

This example makes sure that you can only change the slider’s value by 1 with each move.

Change color of the slider

In order to change the color of the slider, use the accentColor() modifier:

Slider (value: $sliderValue, in: 0 ... 20 , step: 1 ) . accentColor ( Color . green )

Slider in SwiftUI with custom color

Add border around the slider

In order to add a rectangular border with a specified width around the slider, use the border() modifier:

Slider (value: $sliderValue, in: 0 ... 20 , step: 1 ) . padding () . accentColor ( Color . green ) . border ( Color . green , width: 2 )

SwiftUI Slider with Rectangular border

In order to add a rectangular border with rounded corners, use the combination of overlay() and RoundedRectangle shape:

Slider (value: $sliderValue, in: 0 ... 20 , step: 1 ) . padding () . accentColor ( Color . green ) . overlay ( RoundedRectangle (cornerRadius: 15.0 ) . stroke (lineWidth: 2.0 ) . foregroundColor ( Color . green ) )

SwiftUI Slider with Rounded Rectangle border

Add SF Symbols (or images) to each side of the slider

Wrap the slider in an HStack and add SF Symbols before and after the slider:

HStack { Image (systemName: "minus" ) Slider (value: $sliderValue, in: 0 ... 20 , step: 1 ) . accentColor ( Color . green ) Image (systemName: "plus" ) }. foregroundColor ( Color . green )

SF Symbols around slider in SwiftUI

Related tutorials:

Check out Apple’s official documentation of SwiftUI Slider.