IOS swift倒计时器不会停止

Ace*_*Ace 1 timer ios swift 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()


        }


    }


}
Run Code Online (Sandbox Code Playgroud)

luk*_*302 6

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

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