IOS swift倒数计时器不会停止

标签 ios swift timer swift2

我正在尝试制作一个倒数计时器,它从 60 秒开始倒计时,然后在倒数到 0 时停止。但是计时器一直在倒计时。任何建议表示赞赏。代码:

@IBOutlet var timeCounter: UILabel!
var second = 60

var timer = NSTimer()

var timerRunning = true

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.


    setTimer()
    timerCounting()
 }

func setTimer(){
    second  -= 1
    timeCounter.text = "\(second)"


}

func timerCounting(){
    if(timerRunning == true){

        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setTimer"), userInfo: nil, repeats: true)
        timerRunning = true
        if second == 0 {
            timerRunning = false
            timer.invalidate()


        }


    }


}

最佳答案

您必须将失效移动到 setTimer 函数中,因为在它的当前位置将永远不会被触发,因为 timerCounting 仅在开始时被调用一次。

func setTimer(){
    second  -= 1
    timeCounter.text = "\(second)"
    if second == 0 {
        timerRunning = false
        timer.invalidate()
    }
}

关于IOS swift倒数计时器不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34471966/

相关文章:

ios - 应用程序显示在 iphone App Store 但未显示在 ipad AppStore

ios - UICollectionView 和弹性单元格

Swift 客户端和根 SSL 证书身份验证

ios - 转到当前 View Controller 的新实例

swift - 如何在 Swift 中获得尽可能小的 Float

c++ - 看门狗定时器

ios - 隐藏标签栏导航 Controller 中的后退按钮

ios - 有可能发展通行证创作者吗?

使用闭包在循环中创建的javascript计时器或间隔

安卓定时器替代品