简体   繁体   中英

Swift: How to start NSTimer once ViewController is opened

My storyboard goes like this: MainNavViewController --> TimerViewController

The TimeViewController contains the NSTimer and the code which manages it.

The NSTimer should AUTOMATICALLY start to countdown once the TimerViewController is opened.

The timer should countdown from 02:00 minutes up to 00:00.

The timer is needed in the said ViewController only, not in the next or the one before it.

Currently, I have the code below:

var timer = NSTimer()
let timeInterval:NSTimeInterval = 0.05
let timerEnd:NSTimeInterval = 0.0
var timeCount:NSTimeInterval = 120.0

func timerDidEnd(timer:NSTimer){
    timeCount = timeCount - timeInterval
    if timeCount <= 0 {
    TimerLabel.text = "Time's Up!"
    timer.invalidate()
    }
}

func timeString(time:NSTimeInterval) -> String {
    let minutes = Int(time) / 60
    let seconds = time - Double(minutes) * 60
    return String(format:"%02i:%02i",minutes,Int(seconds))
}

func StartTimer() { // Function called in viewDidLoad
    if !timer.valid{
    TimerLabel.text = timeString(timeCount)
    timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval,
    target: self,
    selector: "timerDidEnd:",
    userInfo: nil,
    repeats: true)
    }
}

HOWEVER, the code won't work and the timerLabel is just set at 02:00 WITHOUT running (counting down).

You forgot to set the text every time the timer function is called

func timerDidEnd(timer:NSTimer){
    timeCount = timeCount - timeInterval
    if timeCount <= 0 {
        TimerLabel.text = "Time's Up!"
        timer.invalidate()
    // Start edit
    } else {
        TimerLabel.text = timeString(timeCount)
    }
    // End edit
}

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