Swift如何防止多次NSTimer.scheduledTimerWithTimeInterval

Swift how to prevent multiple NSTimer.scheduledTimerWithTimeInterval

我一直在做秒表。

启动、停止和暂停操作效果很好。

但是,当我点击两次开始操作时

time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

这个动作重新开始,时间运行更快!

我如何阻止该操作?

提前致谢!!!

您需要在 class 的顶部声明一个变量:

 var timer = NSTimer()

然后在开始按钮中分配这个计时器变量,如下所示:

@IBAction func startTimerButtonTapped(sender: UIButton) {
   time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}

无论什么时候你想停止这个定时器,你都需要使它无效,像这样:

timer.invalidate()

如果想再点击两次开始按钮,需要先让其失效再调度:

@IBAction func startTimerButtonTapped(sender: UIButton) {
       timer.invalidate()
       time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
    }

希望对您有所帮助。

我找到了一个简单的答案!!!

但是,上面的答案比我找到的答案简单。

我发现的是

我只需要声明一个变量就可以了

var isStop = true

然后

Timer.scheduledTimerWithTimeInterval()

运行我需要放

isStop = false

还有每次暂停和停止动作 我需要放

isStop = true

谢谢大家提醒我换位思考!!