UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Slider finished changing

Forums > SwiftUI

How would I call a function only when a Slider finishes sliding?

I want to use a slider to select a value from a range, and then once that value is selected, call a function to do some other action. Using the code below, the value changes with every smidge of movement. If I do something like my own Binding for get/set, that would make a ton of actions being taken, all of which would not be needed until the final number is arrived at.

NOTE: It looks like in UIKit, the UISlider, setting a property like this would do it:

    slider.isContinuous = false 

...but not finding anything simiar in SwiftUI Slider.

Here's the code:

 struct ContentView: View {
    @State private var value: Double = 0.0

    var body: some View {
        Slider(value: $value, in: -0.5...0.5)
        Text("Value will be:: \(value, specifier: "%.1f")")
    }

    // The function I'd like to call when the above slider is finished being changed.
    func sliderCompleted() {
        // call and do some other action...
    }
}

4      

You can supply an onEditingChanged closure to Slider and it will get called with a value of true when the user starts moving the slider thumb and false when they stop.

    Slider(value: $value, in: -0.5...0.5) { editing in
        print(editing)
    }

7      

Thanks roosterboy. Should have known it was something straight forward...works perfectly!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.