Search code examples
iosswiftuser-interfaceuislideruianimation

UISlider set value


I have a UISlider and I want to set its value from 1 to 10. The code I use is.

let slider = UISlider()
slider.value = 1.0
// This works I know that
slider.value = 10.0

What I want to do is animate the UISlider so that it takes 0.5s to change. I don't want it to be as jumpy more smooth.

My idea so far is.

let slider = UISlider()
slider.value = 1.0
// This works I know that
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animation: { slider.value = 10.0 } completion: nil)

I am looking for the solution in Swift.


Solution

  • EDITED

    After some discussion, I thought I'd clarify the differences between the two suggested solutions:

    1. Using the built-in UISlider method .setValue(10.0, animated: true).
    2. Encapsulating this method in a UIView.animateWithDuration.

    Since the author is asking explicitly for a change that will take 0.5s---possibly triggered by another action---the second solution is to prefer.

    As an example, consider that a button is connected to an action that sets the slider to its maximum value.

    @IBOutlet weak var slider: UISlider!
    
    @IBAction func buttonAction(sender: AnyObject) {
        // Method 1: no animation in this context
        slider.setValue(10.0, animated: true)
    
        // Method 2: animates the transition, ok!
        UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: {
            self.slider.setValue(10.0, animated: true) },
            completion: nil)
    }
    

    Running a simple single UIVIewController app with just the UISlider and UIButton objects present yields the following results.

    • Method 1: Instant slide (even though animated: true)
    • Method 2: Animates transition. Note that if we set animated: false in this context, the transition will be instantaneous.