在 Swift 中自动移动 UISlider [英] Move UISlider automatically in Swift
问题描述
我想在您点击按钮时将 UISlider 从 minValue 循环移动到 maxValue 并在再次点击按钮时将其停在当前位置,我想使用 Swift.
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.
我遇到的主要问题是函数 slider.setValue() 太快了,我希望动画更慢.
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)
}
推荐答案
您可以使用时间自动移动滑块.在全局范围内创建 NSTimer 变量:同时在全局范围内创建一个 Bool 变量,用于检查是否需要修改.
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)
在 tImer Action 上,您可以编写代码来更改 Slider 的值:
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
}
这篇关于在 Swift 中自动移动 UISlider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!