Customizing the Slider in SwiftUI


In SwiftUI, we can use the Slider control to give the user ability to choose a value from a given range. By default, the Slider looks like you can see below:

SwiftUI Slider

As you can see, the default slider in SwiftUI is a blue line. But you may want to customize it a little bit.

Well, there are limited options available today to customize the SwiftUI Slider. You can change the slider line color of the left part, set the background color, change the width.

Change line color of the slider

Below is how to change the slider line color using tint():

            Slider(value: $volume, in: 0...100, step: 1)
                .tint(Color.green)

We can also use the accentColor() to change the color:

            Slider(value: $volume, in: 0...50, step: 1)
                .accentColor(Color.yellow)
            

Set the background color of the SwiftUI Slider

We can use the accentColor() to change the slider background color:

            Slider(value: $volume, in: 0...50, step: 1)
                .background(Color.yellow)
            

The above program will set the background of the slider to yellow.

Change Slider width

You can change the width of the slider using the frame() method as you can see below. For example, if you want to set the width of the slider to 235, you can use the frame() like you can see below:

            Slider(value: $volume, in: 0...50, step: 1)
                .frame(width: 235)

Invert the color

Using the colorInvert, you can invert the colors of the slider. Below is a given program for slider that will invert the color:


            Slider(value: $volume, in: 0...50, step: 0.2)
                .colorInvert()

The above slider will look like as you can see in the figure below:

Slider with colorInvert in SwiftUI