Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my UISlider animating?

According to Apple's documentation, it is possible to programmatically set the value of a UISlider with a smooth animation. I'm attempting to do so from a custom view controller, the UI is being defined from a storyboard.

The Context

In my example I'm attempting to update the slider value from a custom view controller, the UI is being defined from a storyboard. The example only renders a single slider.

When the user releases the slider, the value is reset to 0.

The Code

import UIKit

class ViewController: UIViewController {

    @IBOutlet var mySlider: UISlider!
    @IBAction func resetSlider() {
        mySlider.setValue(0, animated:true)
        NSLog("Reset!")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

resetSlider is linked to the Touch Up Inside event.

The Problem

When resetSlider is called the value does change on the interface, but it does not animate (the value simply "jumps" to 0). My goal is to have the value gracefully shift back to zero.

Note: "Reset!" only displays once (per click), which indicates that resetSlider is not being called multiple times.

Why isn't this UISlider animating?

The Video

Since IB is so visual, here is a video of the situation, password is code

like image 929
slifty Avatar asked Mar 06 '15 19:03

slifty


1 Answers

the setValue animated parameter doesn't actually perform an animation, but rather it enables animation.

To trigger the animation, you need to use UIView.animateWithDuration, and pass in the setValue command as the animation:

UIView.animateWithDuration(0.2, animations: {
  self.mySlider.setValue(0, animated:true)
})

Swift 5

UIView.animate(withDuration: 0.2, animations: {
  self.mySlider.setValue(0, animated:true)
})
like image 153
f3n1kc Avatar answered Sep 26 '22 04:09

f3n1kc