从另一个函数中取消Swift定时器

时间:2021-04-09 16:04:18

I am using a Swift Timer library found here. It allows you to run a timer and then stop it using the following syntax:

我正在使用这里找到的Swift Timer库。它允许您运行计时器,然后使用以下语法将其停止:

Timer.every(5.seconds) { (timer: Timer) in
    // do something

    if finished {
        timer.invalidate()
    }
}

I am trying to have the timer start and then have the option of the timer being cancelled from another function but I can't figure out how to reference the timer that is counting down from another function. I have tried doing something like this but it throws the following error:

我试图让计时器启动,然后可以选择从另一个功能取消计时器,但我无法弄清楚如何引用从另一个功能倒计时的计时器。我尝试过这样的事情,但它会引发以下错误:

Static member every cannot be used on instance of type Timer

每个静态成员都不能在Timer类型的实例上使用

   var countTimer = Timer()

        override func viewDidLoad() {
            super.viewDidLoad()

            initNotificationSetupCheck()

           countTimer.every(5.seconds) { //error here

        }

     func stopTimer() {

           countTimer.invalidate()

           }

2 个解决方案

#1


1  

What if you were to use a mixture of both, but instead of creating an instance of Timer, assign the timer from inside the closure to your member variable like:

如果您要使用两者的混合,但是不是创建Timer的实例,而是将闭包内的计时器分配给您的成员变量,如下所示:

var countTimer: Timer
Timer.each(5.seconds) { timer in
    countTimer = timer
    //rest of code
}

Then you can invalidate the timer outside of the closure if needed.

然后,如果需要,您可以在闭包之外使计时器无效。

#2


0  

You can go like this

你可以这样

self.timer = Timer.scheduledTimer(timeInterval: 5, target: self,
                                  selector: #selector(self.eventForTimer), userInfo: nil, repeats: true)

for cancelling timer

用于取消计时器

func cancelTimer() {
    self.timer.invalidate()
}

#1


1  

What if you were to use a mixture of both, but instead of creating an instance of Timer, assign the timer from inside the closure to your member variable like:

如果您要使用两者的混合,但是不是创建Timer的实例,而是将闭包内的计时器分配给您的成员变量,如下所示:

var countTimer: Timer
Timer.each(5.seconds) { timer in
    countTimer = timer
    //rest of code
}

Then you can invalidate the timer outside of the closure if needed.

然后,如果需要,您可以在闭包之外使计时器无效。

#2


0  

You can go like this

你可以这样

self.timer = Timer.scheduledTimer(timeInterval: 5, target: self,
                                  selector: #selector(self.eventForTimer), userInfo: nil, repeats: true)

for cancelling timer

用于取消计时器

func cancelTimer() {
    self.timer.invalidate()
}