How to add 5 seconds to a timer

旧街凉风 提交于 2019-12-11 03:57:01

问题


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()
    }
}

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:

fatal error: floating point value can not be converted to UInt8 because it is less than UInt8.min

What's the correct way to add 5 seconds to the timer?


回答1:


Invalidate the timer, then create a new one. You can't modify the time interval of a timer.

As far as your error, elapsedTime is probably negative, which yields the error. UInt8.min is 0.

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.



来源:https://stackoverflow.com/questions/32127138/how-to-add-5-seconds-to-a-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!