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
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With