How to add 5 seconds to a timer

2019-07-17 09:09发布

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条回答
太酷不给撩
2楼-- · 2019-07-17 09:55

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.

查看更多
登录 后发表回答