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



在此处输入图像描述

我怎样才能停止循环?

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

相关内容

  • 没有找到相关文章

最新更新