问题描述
我需要将标签倒计时从20秒降低到0,然后重新开始。这是我第一次在Swift中进行项目,并且尝试使用 NSTimer.scheduledTimerWithTimeInterval
。此倒计时应在给定的时间内循环运行。
I need to have a label countdown from 20secs to 0 and start over again. This is my first time doing a project in Swift and I am trying to use NSTimer.scheduledTimerWithTimeInterval
. This countdown should run in a loop for a given amount of times.
我很难实施开始和开始方法(循环)。我基本上找不到20秒开始计时的方法,当结束时,请重新开始计时。
I am having a hard time implementing a Start and Start again method (loop). I basically am not finding a way to start the clock for 20s and when it's over, start it again.
我很欣赏如何操作
Wagner的任何想法
I'd appreciate any idea on how to do thatWagner
@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)"
}
推荐答案
您应该从现在开始将日期endTime设置为20s,然后只需检查日期timeIntervalSinceNow。一旦timeInterval达到0,则将其设置为从现在起20秒
You should set your date endTime 20s from now and just check the date timeIntervalSinceNow. Once the timeInterval reaches 0 you set it 20 seconds from now again
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var strTimer: UILabel!
var endTime = NSDate().dateByAddingTimeInterval(20)
var timer = NSTimer()
func updateTimer() {
let remaining = endTime.timeIntervalSinceNow
strTimer.text = remaining.time
if remaining <= 0 {
endTime = NSDate().dateByAddingTimeInterval(20)
}
}
override func viewDidLoad() {
super.viewDidLoad()
strTimer.text = "20:00"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension NSTimeInterval {
var time:String {
return String(format:"%02d:%02d", Int((self) % 60 ),Int(self*100 % 100 ) )
}
}
这篇关于使用NSTimer以秒为单位的倒数计时(从00:20到0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!