I need to have a label countdown from 20 seconds to zero and start over. This is my first Swift project, and I'm trying to use NSTimer.scheduledTimerWithTimeInterval . This countdown should be performed in a loop a certain number of times.
I find it difficult to implement the Start and Start again method (loop). I basically do not find a way to start the clock for the 20s, and when it is over, start it again.
I would be grateful for any idea on how to do this Wagner
@IBAction func startWorkout(sender: AnyObject) { timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("countDownTime"), userInfo: nil, repeats: true) startTime = NSDate.timeIntervalSinceReferenceDate() } func countDownTime() { var currentTime = NSDate.timeIntervalSinceReferenceDate() //Find the difference between current time and start time. var elapsedTime: NSTimeInterval = currentTime - startTime //calculate the seconds in elapsed time. let seconds = UInt8(elapsedTime) elapsedTime -= NSTimeInterval(seconds) //find out the fraction of milliseconds to be displayed. let fraction = UInt8(elapsedTime * 100) //add the leading zero for minutes, seconds and millseconds and store them as string constants let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds) let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction) //concatenate minuets, seconds and milliseconds as assign it to the UILabel timeLabel.text = "\(strSeconds):\(strFraction)" }
source share