简体   繁体   English

iOS快速倒数计时器不会停止

[英]IOS swift countdown timer will not stop

I am attempting to make a countdown timer that counts down from 60 seconds and then stops when it gets to 0. But for the timer keeps going into negative seconds. 我正在尝试制作一个倒计时计时器,该计时器从60秒开始倒计时,然后在计数到0时停止计时。 Any advice is appreciated. 任何建议表示赞赏。 Code: 码:

@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()


        }


    }


}

You have to move the invalidation into the setTimer function since at its current location will never be triggered because timerCounting is only called once - in the beginning. 您必须将无效性移到setTimer函数中,因为永远不会触发它的当前位置,因为timerCounting仅在开始时被调用一次。

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

play with this in playground 在操场上玩这个

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Foundation


@objc class C:NSObject {
    var timer: NSTimer?
    var second = 5
    func setTimer(){
        if c.second < 0 {
            print("the timer fires the last time here ...")
            timer?.invalidate()
        } else {
            print(second)
            second  -= 1
        }
    }
}

let c = C()

func timerCounting(){
        c.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: c, selector: Selector("setTimer"), userInfo: nil, repeats: true)
}

timerCounting()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM