为什么我的秒表上的启动按钮会在按下停止后重置计时器?一切正常,直到我停止计时器,然后重新启动它。它应该从停止的位置继续,但它会将计时器重置为0.这是我的代码:
类ViewController:UIViewController {
var timer = NSTimer()
var startTime = NSTimeInterval()
@IBOutlet var displayTimeLabel: UILabel!
@IBAction func start(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)
}
startTime = NSDate.timeIntervalSinceReferenceDate()
}
@IBAction func stop(sender: AnyObject) {
timer.invalidate()
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTime
let hours = UInt8(elapsedTime / 3600)
elapsedTime -= (NSTimeInterval(hours) * 3600)
let minutes = UInt8(elapsedTime / 60)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
let strHours = String(format: "%02d", hours)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
displayTimeLabel.text = "\(strHours):\(strMinutes):\(strSeconds):\(strFraction)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
每次调用startTime
方法时,您都要设置start
。您只想在第一次调用时执行此操作。您可以使用选项来正确地确定状态,并且只在最初为零时设置startTime
。
然后,您可以使用仅设置startDate = nil
class ViewController: UIViewController {
var timer : NSTimer?
var startTime? : NSTimeInterval?
var accumulatedTime = NSTimeInterval()
@IBOutlet var displayTimeLabel: UILabel!
@IBAction func start(sender: AnyObject) {
guard self.timer == nil else {
return
}
self.startTime = NSDate.timeIntervalSinceReferenceDate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)
}
@IBAction func stop(sender: AnyObject) {
guard self.timer != nil else {
return
}
self.timer!.invalidate()
self.timer = nil
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
let intervalTime = currentTime - startTime!
self.startTime = currentTime
self.accumulatedTime += intervalTime
var elapsedTime = self.accumulatedTime
let hours = UInt8(elapsedTime / 3600)
elapsedTime -= (NSTimeInterval(hours) * 3600)
let minutes = UInt8(elapsedTime / 60)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
let timeString = String(format:"%02d:%02d:%02d.%02d",hours,minutes,seconds,fraction)
displayTimeLabel.text = timeString
}
}