ios - 如何给计时器加 5 秒

标签 ios swift nstimer nstimeinterval uint8t

我正在尝试制作一个显示以下内容的计时器 - 小时:分钟:秒:毫秒。这是我的代码:

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 秒的正确方法是什么?

最佳答案

使计时器无效,然后创建一个新计时器。您不能修改计时器的时间间隔。

就您的错误而言,elapsedTime 可能为负数,这会产生错误。 UInt8.min0

计时器不是秒表。 NSTimer 在特定时间触发。

对于像秒表这样的东西,您应该简单地设置一个开始日期。然后,您可以使用设置为一秒的计时器每秒更新一次显示。您将显示当前时间和开始日期之间的差异。

关于ios - 如何给计时器加 5 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127138/

相关文章:

iphone - 在 ios 中将字符串中的两个值加在一起

objective-c - 使用类别将数据添加到 UIView

ios - 使用 UILabel 的持续时间动画表现得很奇怪

ios - 为什么在 Xcode 11 上,UICollectionViewCell 一旦滚动就会改变大小(我已经在 sizeForItem AtIndexPath :)? 中设置了大小

swift - 不同国家的不同应用程序名称

ios - iPad : need accurate alternative to NSTimer for making donkey kong style game

c# - MvxTableViewCell 上的属性文本

ios - 重用导航栏按钮

swift - 在 Swift 中创建一个包含多个数组的数组

iphone - 无法使(停止)NSTimer 无效