DEV Community

Cover image for How to call a function when a slider changes in SwiftUI
Maegan Wilson
Maegan Wilson

Posted on • Edited on • Originally published at cctplus.xyz

How to call a function when a slider changes in SwiftUI

There are times you might want to call a function when a slider changes in SwiftUI. I did this recently to send out the slider's value to another device when the slider is moving. I couldn't wait to send out the final value since that would be a delayed response for the user.

After the code example, I'll explain the three steps.

import SwiftUI

struct SliderExample: View {
// 1. declare a state for the value of the slider
    @State private var value: Float = 0.0

// 2. create a slider with a new Binding variable
    var body: some View {
        Slider(value: Binding(
            get: {
                self.value
            },
            set: {(newValue) in
                  self.value = newValue
                  self.doSomething()
            }
        ))
    }

// 3. create the function to call when the slider changes value    
    func doSomething(){
        print("\(value)")
    }
}
Enter fullscreen mode Exit fullscreen mode

1. Declare a state variable for the value of the slider

This is the variable that the slider is currently. It needs to be declared with a State property wrapper since the value is going to change. It also needs to have a Float type since a Slider needs a Binding<Float>.

2. Create a slider with a new binding variable

In this step, we are creating a Binding variable. A Binding variable is a computed property. By creating it as the value that the slider is using, we can utilize the setter to call the function every time the value is changing.

3. Create the function to call when the slider changes value

Make sure to make the function that you need to call when the slider changes values.


If you enjoy my posts, please consider sharing it or Buying me a Coffee!

Buy Me A Coffee

Top comments (4)

Collapse
 
lucianoschillagi profile image
Luko • Edited

Hello, I have a question:

How can I detect, when the user moves the slider if the value is incrementing or decrementing?

If the user moves up the slider I need to call a method (for instance: volume up)

If the user moves down the slider I need to call a method (for instance: volume down)

thanks!

Collapse
 
lucianoschillagi profile image
Luko
Collapse
 
retch profile image
Retch • Edited

Helped me a lot, but in "set:" it should be called either newVal or newValue.

Collapse
 
maeganwilson_ profile image
Maegan Wilson

Thanks for catching that! I'll update the post :)