Change SwiftUI Slider value on tapping a Button


In this tutorial, you will learn how to change the value of a SwiftUI Slider control when a button is tapped.

Changing the state variable value of the slider is quite easy. We just have to assign a new value to the variable. All we need to do the things are in the button action.

Before we go forward, first create our Slider:

 
    @State private var volume: Double = 77
    
    var body: some View {
        
        VStack {
            
            Slider(value: $volume, in: 0...100, step: 0.2)
            
            Text("Volume is \(volume)")
            
        }
        
    }

We can swipe left and right to decrease the value of the state variable. But we also want to change the value of the Slider variable when clicking a button.

So let’s create a button inside the VStack. Below is our button design:

      ...
            Button(action: {
                // Code to change the Slider variable value
                volume = 17.4
            }, label: {
                Text("Change Slider Value")
            }).padding(4).background(.green).foregroundColor(.white)
            
      ...

In the above program, you can see that we are changing the value of the state variable volume. Changing the value also changes the position of the slider to the position of the specific value we assigned in the button action.

Complete code to change the slider value on a Button tap

Below is given the complete code of the Swift file for changing the position or value of SwiftUI Slider control when tapping a button:

import SwiftUI

struct ContentView: View {
    
    @State private var volume: Double = 77
    
    var body: some View {
        
        VStack {
            
            Slider(value: $volume, in: 0...100, step: 0.2)
            
            Text("Volume is \(volume)")
            
            Button(action: {
                // Change slider position by changing the value
                volume = 17.4
            }, label: {
                Text("Change Slider Value")
            }).padding(4).background(.green).foregroundColor(.white)
            
        }
        
    }
    
}

Below is given what is happening when we run it on an iOS device or the Xcode emulator:

Change SwiftUI Slider Value on button tap