Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a function when a Slider changes in SwiftUI?

I'm trying to trigger the sliderchanged() function when the slider value changes, I might be missing something very basic but every similar thing I've found isn't working. Isn't there anything like "action" for the Slider or the old "ValueChanged" action?

Here's my code:

struct CustomSlider1: View {

    @State var progress: Float = 0.5
    var body: some View {

       VStack{
        Slider(value: $progress)
            .padding(.all)
            Text(String(progress))          
        }        
    }

    func sliderchanged() {
        //do things 
    }
}

Thanks!!

like image 942
Gianclgar Avatar asked Oct 16 '19 01:10

Gianclgar


1 Answers

You can make a custom Binding that calls the function in the Binding's setter:

@State var progress: Float = 0.5
var body: some View {

   VStack{
       Slider(value: Binding(get: {
           self.progress
       }, set: { (newVal) in
           self.progress = newVal
           self.sliderChanged()
       }))
       .padding(.all)
       Text(String(progress))
    }
}

func sliderChanged() {
    print("Slider value changed to \(progress)")
}
like image 58
RPatel99 Avatar answered Sep 28 '22 11:09

RPatel99