Timer.scheduled();我无法停止变量++循环

Timer.scheduled(); I cannot stop variable++ cycle

enter image description here

我怎样才能停止循环?

代码 1

 @objc func dismissImageView() {
    timer1 = Timer()
    timer1 = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerWillDisappear), userInfo: nil, repeats: true)
    
}

代码 2

   **When i touch on myView - timer's beginning and don't stop!**
@objc func timerWillDisappear() {
    if repeatsVar != 1.0 {
        repeatsVar! += 0.01
    } 
}

代码 3

else if repeatsVar == 1.0 { **This if doesn't work!!!**
            timer1.invalidate()
            timer1 = nil
            repeatsVar! -= 1
            self.view.removeFromSuperview()
        }

浮点数有一些错误。您可能不会得到恰好为 1.0 的值。既然你一达到 1.0 就停止,为什么不检查它是否小于 1.0 呢?

@objc func timerWillDisappear() {
    if repeatsVar < 1.0 {
        repeatsVar += 0.01
    } else 
        timer1.invalidate()
        timer1 = nil
        repeatsVar = 0
        self.view.removeFromSuperview()
    }
}

另请注意,您的 dismissImageView() 方法不应先创建一个空计时器,然后再创建一个预定计时器:

@objc func dismissImageView() {
    //timer1 = Timer() <- Get rid of this line.
    timer1 = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerWillDisappear), userInfo: nil, repeats: true)
}