2
我正在嘗試使計時器顯示以下 - 小時:分鐘:秒:毫秒。這是我的代碼:如何將5秒添加到計時器
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秒,然後我們會擔心全球部分)。我試圖改變/添加以下內容:
var seconds = UInt8(elapsedTime)
seconds += 5 // Error here...
elapsedTime -= NSTimeInterval(seconds)
,但我得到一個錯誤說:
fatal error: floating point value can not be converted to UInt8 because it is less than UInt8.min
什麼是5秒添加到計時器的正確方法是什麼?
感謝您的回答!聽起來不錯!我如何檢索原始計時器的值,然後將相同時間分配給新計時器,並添加5秒? – Horay
我更新了我的答案以進一步解釋。 –
我很困惑。是不是我在func updateTime()的前兩行做過的? – Horay