【发布时间】:2015-06-04 19:54:53
【问题描述】:
我需要从 20 秒到 0 进行标签倒计时,然后重新开始。这是我第一次在 Swift 中做一个项目,我正在尝试使用NSTimer.scheduledTimerWithTimeInterval。这个倒计时应该循环运行给定的次数。
我很难实现 Start 和 Start again 方法(循环)。我基本上没有找到一种方法来启动 20 秒的时钟,当它结束时,重新启动它。
如果您有任何关于如何做到这一点的想法,我将不胜感激 瓦格纳
@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)"
}
【问题讨论】: