Starting timer on button click in swift

2019-09-06 19:37发布

Ive created a timer in swift to move a UISlider from one end to another again and again when a button is pressed. But I'm always getting a breakpoint at the timer line, although everything should be right.

@IBAction func setSliderValue(_ sender: UIButton){
        mytimer =  Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }


    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)
        }
        else 
        {
            slider.setValue(0, animated: true)
        }
    }

标签: ios swift timer
2条回答
Animai°情兽
2楼-- · 2019-09-06 20:07

The check of your function is incorrect.

func timerAction(){
    let range =  slider.maximumValue - slider.minimumValue
    let increment = range/100
    let newval = slider.value + increment
    if newval <= slider.maximumValue {
        slider.setValue(newval, animated: true)
    } else {
        slider.setValue(slider.minimumValue, animated: true)
    }
}

Also, in your event handler, should invalidate the timer (if it's not nil) first before instancing a new one.

查看更多
【Aperson】
3楼-- · 2019-09-06 20:11

Its working now with the following code, though the slider is only moving from left to right until it gets 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)
        }
    }
查看更多
登录 后发表回答