Move UISlider automatically in Swift

試著忘記壹切 提交于 2019-12-10 22:09: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)
}

回答1:


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
  }



回答2:


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)
        }
    }


来源:https://stackoverflow.com/questions/41361451/move-uislider-automatically-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!