如何为计时器增加5秒 [英] How to add 5 seconds to a timer
问题描述
我正在尝试使计时器显示以下内容-小时:分钟:秒:毫秒.这是我的代码:
I'm trying to make a timer showing the following - hours : minutes : seconds : milliseconds. Here is my code:
var timer = NSTimer()
var startTime = NSTimeInterval()
func updateTime()
{
var currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime : NSTimeInterval = currentTime - startTime
let hours = UInt8(elapsedTime / 3600.0)
elapsedTime -= (NSTimeInterval(hours) * 3600)
let minutes = UInt8(elapsedTime / 60.0)
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)
timeLabel.text = "\(strHours):\(strMinutes):\(strSeconds):\(strFraction)"
}
@IBAction func start(sender: AnyObject) {
if !timer.valid {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
}
如何通过其他方法将5秒添加到计时器? (显然,我必须创建一个全局var
,但我现在想使其保持简单,首先实际添加5秒,然后我们担心全局部分.)我尝试更改/添加以下内容:
How can I add 5 seconds to the timer in another method? (Obviously I will have to make a global var
, but I'm trying to keep it simple for now and first actually add the 5 secs, then we'll worry about the global part.) I tried changing/adding the following:
var seconds = UInt8(elapsedTime)
seconds += 5 // Error here...
elapsedTime -= NSTimeInterval(seconds)
但我收到一条错误消息:
But I get an error saying:
致命错误:无法将浮点值转换为UInt8 因为它小于UInt8.min
fatal error: floating point value can not be converted to UInt8 because it is less than UInt8.min
向计时器添加5秒的正确方法是什么?
What's the correct way to add 5 seconds to the timer?
推荐答案
使计时器无效,然后创建一个新计时器.您无法修改计时器的时间间隔.
Invalidate the timer, then create a new one. You can't modify the time interval of a timer.
就您的错误而言,elapsedTime
可能为负,从而产生错误. UInt8.min
是0
.
As far as your error, elapsedTime
is probably negative, which yields the error. UInt8.min
is 0
.
计时器不是秒表. NSTimer
在特定时间触发.
A timer is not a stop watch. An NSTimer
fires off at a specific time.
对于秒表之类的东西,您只需设置开始日期即可.然后,您可以使用设置为一秒的计时器来每秒更新一次显示.您将显示当前时间和开始日期之间的时差.
For something like a stop watch, you should simply be setting a start date. Then, you could use a timer that's set to one second to update the display every second. You'd display the difference between the current time and the start date.
这篇关于如何为计时器增加5秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!