Move UISlider automatically in Swift

2019-08-01 06:41发布

I want to move a UISlider from minValue to maxValue in a loop when you hit a button and stop it at the current position when hitting the button again, I want to use Swift.

The main problem i got is that the function slider.setValue() is way to fast, I want the animation more slowly.

@IBAction func setSliderValue(_ sender: UIButton){
        slider.setValue(100, animated: true)
        print("The value of the slider is now \(slider.value)")
        sliderValue = Int(slider.value)
}

2条回答
Summer. ? 凉城
2楼-- · 2019-08-01 07:02

This code is working, though the slider only moves from left to right, not from right to left when he reached maximumValue, it should move from left to right and then right to left until the invalidated.

@IBAction func setSliderValue(_ sender: UIButton){
        mytimer =  Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        /*slider.setValue(100, animated: true)
        print("The value of the slider is now \(slider.value)")
        sliderValue = Int(slider.value)*/
    }


    func timerAction(){
        let Range =  slider.maximumValue - slider.minimumValue;
        let Increment = Range/100;
        let newval = slider.value + Increment;
        if(Increment <= slider.maximumValue)
        {
            slider.setValue(newval, animated: true)
            print("The value of the slider is now \(slider.value)")
            sliderValue = Int(slider.value)
        }
        else if (Increment >= slider.minimumValue)
        {
            slider.setValue(newval, animated: true)
        }
    }
查看更多
闹够了就滚
3楼-- · 2019-08-01 07:09

You can use time to Automatically Move slider. Create NSTimer variable in global scope: Also create one Bool variable in global scope for checking if Need to revise it.

var  mytimer : NSTimer?
var  reversing : Bool?

start timer when you want to animate it:

reversing = NO;
mytimer =  NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

On tImer Action, You can write code to change value of Slider:

var sliderrange =  slider.maxValue - slider.minValue;
var increment = sliderrange/100;
var newval = slider.value;

newel = reversing ? (slider.value - increment) : (slider.value + increment);

if(newval >= slider.maxValue)
{
  reversing = true;
   newval = newval - 2*increment;

}
else  if(newel <= 0)
{
  reversing = false;
}
 slider.setValue(newval, animated: true)

On Button Action, You can just stop the timer,

 if mytimer != nil {
    mytimer!.invalidate()
    mytimer = nil
  }
查看更多
登录 后发表回答