coding22 coding22 - 1 year ago 69
iOS Question

How do I slowly move my UISlider to the left or right with a touch of a button?

I have these two buttons and if I press on the button on the left I want the slider to move slowly all the way to the left and the same thing when I press the button on the right to move the slider all the way to the right. The code I have right now moves the slider really quickly and I want it to be gradually.

override func didMoveToView(view: SKView) {

middleSlider = UISlider(frame: CGRectMake(self.view!.bounds.width/2 - 150/2, self.view!.bounds.height/2 * 1.7, 150, 50))
middleSlider.tintColor = UIColor.whiteColor()
middleSlider.minimumTrackTintColor = UIColor.whiteColor()
middleSlider.maximumTrackTintColor = UIColor.whiteColor()
middleSlider.setThumbImage(UIImage(named: "mixerb1"), forState: UIControlState.Normal)
middleSlider.maximumValue = 2.0
middleSlider.minimumValue = 0.0
middleSlider.value = 1.0
middleSlider.continuous = true
middleSlider.userInteractionEnabled = true
middleSlider.addTarget(self, action: #selector(middleSliderChangeAudio), forControlEvents: UIControlEvents.AllEvents)


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)

if == "left" {
print("slider moves to left")

UIView.animateWithDuration(10.0, animations: {
self.middleSlider.value = self.middleSlider.minimumValue
self.middleSlider.continuous = true

if == "right" {
print("slider moves to right")

UIView.animateWithDuration(10.0, animations: {
self.middleSlider.value = self.middleSlider.maximumValue
self.middleSlider.continuous = true

Answer Source

Use the setValue(_:animated:) method here Documentation. Let us know how it goes .

Once you added this, wrap it in your animate with duration like this. Note that 10 seconds is just a hardcoded value, change the duration to whatever you want, same goes to the value that you wanted to set.

@IBAction func moveSlider(sender: UIButton) {
    UIView.animateWithDuration(10, animations: {
        self.slider.setValue(1.0, animated: true)


While you're at it, scroll up a bit to check out the documentation for the property value. So you have a better understanding of what's going on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download