首页 > 解决方案 > 快速计时器不会停止

问题描述

代码:

var timerCount: Int = 15

hideTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
    self.timerCount -= 1
    print(self.timerCount)
    if self.timerCount <= 0 {
        if self.hideTimer != nil {
            self.hideTimer.invalidate()
            self.hideTimer = nil
        }
    }
})

print 语句只是继续打印成负数 =(

这发生在 UITableViewCell 中,如果这很重要的话。

我究竟做错了什么?

标签: iosswiftxcodetimercounter

解决方案


您在回调中获得对计时器的引用:'(timer)'。使用这个来使您的计时器无效:

var timerCount: Int = 3

let hideTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
    timerCount -= 1
    print(timerCount)
    if timerCount <= 0 {
        timer.invalidate()
    }
})

推荐阅读