【问题标题】:Swift timer won't stop快速计时器不会停止
【发布时间】:2021-06-30 07:25:26
【问题描述】:

代码:

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 中,如果这很重要的话。

我做错了什么?

【问题讨论】:

    标签: ios swift xcode timer counter


    【解决方案1】:

    您在回调中获得对计时器的引用:'(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()
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多