停止单击按钮后执行的计时器

stop the timer which is executed after button click

我有一个计时器,在单击 button 后我希望计时器开始,当 timer 到达 0 时我想停止计时器。我知道我可以用 invalidate() 函数做到这一点,但我无法使用这里的代码

访问计时器
    var timer = 5 {
        didSet {
            label.text = String(timer)
            
        }
    }
    @IBAction func onClickAnimate(_ sender: Any) {
        let timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    @objc func updateCounter(){
        if timer > 0 {
            timer -= 1
        }
        if timer == 0 {
            timer = 5
            timerCount.invalidate() // error is here
            }
    }

如果我决定在全局范围内创建 timerCount,我会得到一个错误 unrecognized selector sent to instance 0x600003b466a0"

将应用任何解决方案

您应该将 timerCount 放在函数外部但放在 class 内部,以便您可以访问它:

class ViewController: UIViewController {
   let timerCount: Timer = Timer()
}

然后,删除 let 关键字。

您现在可以访问您的timerCount

解决方案 1 : 创建一个变量

var timerCount:Timer!
@IBAction func onClickAnimate(_ sender: Any) {
    timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
    if timer > 0 {
        timer -= 1
    }
    if timer == 0 {
        timer = 5
        timerCount.invalidate() 
   }
}

解决方案 2:使用块

Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timerCount in
    if self.timer > 0 {
        self.timer -= 1
    }
    else
    if self.timer == 0 {
        self.timer = 5
        timerCount.invalidate() 
    }
}

Global variable in Class喜欢:

var timerCount = Timer()

砰!!!...现在您可以访问它了。