简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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