Member-only story

How to call a function when a slider changes in SwiftUI

Jay Wilson
2 min readJan 18, 2020

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. Click here for a Gist

import SwiftUIstruct 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)")
}
}

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>.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Jay Wilson
Jay Wilson

Written by Jay Wilson

I like to solve problems using Swift, make YouTube videos, and take photos. I also really enjoy a good cup of coffee.

Responses (2)

Write a response

Thank you! I was trying to do basically this with a didSet on my @State variable but it wasn't getting called. This way works perfectly.

--

Hi
Nice work, but code does not build, can you please update this so it works with the latest Xcode build? thank you.
Also can we do this with a segment picker, which is call a function when a segment is selected?

--