我在写一段代码,我想计算一个按钮被按下的时间.为了做到这一点,我在按下按钮时记录了NSDate(),并在松开按钮时try 使用timeIntervalSinceDate功能.这似乎可行,但我找不到任何方法来打印结果或将其转换为整数.

var timeAtPress = NSDate() 

@IBAction func pressed(sender: AnyObject) {
    println("pressed")
    timeAtPress = NSDate()
}

@IBAction func released(sender: AnyObject) {
    println("released")
    var elapsedTime = NSDate.timeIntervalSinceDate(timeAtPress)
    duration = ???
}

我见过一些类似的问题,但我不懂C,所以我很难理解给出的答案.如果有更有效的方法来确定按钮按下的时间,我愿意听取建议.提前谢谢.

推荐答案

你试图计算elapsedTime是不正确的.在Swift 3中,它将是:

let elapsed = Date().timeIntervalSince(timeAtPress)

注意Date参考后面的().Date()实例化一个新的日期对象,然后timeIntervalSince返回该对象与timeAtPress之间的时间差.这将返回一个浮点值(技术上是TimeInterval).

如果希望将其截断为Int,可以使用:

let duration = Int(elapsed)

顺便说一句,timeAtPress变量的定义不需要实例化Date对象.我想你是有意的:

var timeAtPress: Date!

这将变量定义为Date个变量(隐式展开的变量),但您可能会推迟该变量的实际实例化,直到调用pressed为止.


或者,我经常使用CFAbsoluteTimeGetCurrent(),例如.,

var start: CFAbsoluteTime!

当我想设置startTime时,我会执行以下操作:

start = CFAbsoluteTimeGetCurrent()

当我想计算经过的秒数时,我会执行以下操作:

let elapsed = CFAbsoluteTimeGetCurrent() - start

值得注意的是,CFAbsoluteTimeGetCurrent份文件警告我们:

重复调用此函数不能保证结果单调递增.由于与外部时间参考同步或由于用户明确改变时钟,系统时间可能会减少.

这意味着,如果不幸的是,当其中一个调整发生时,您测量了经过的时间,那么您可能会得到错误的经过时间计算.NSDate/Date计算也是如此.最安全的方法是使用基于mach_absolute_time的计算(最容易使用CACurrentMediaTime):

let start = CACurrentMediaTime()

let elapsed = CACurrentMediaTime() - start

它使用mach_absolute_time,但避免了Technical Q&A QA1398中概述的一些复杂性.

Remember, though, that CACurrentMediaTime/mach_absolute_time will be reset when the device is rebooted. So, bottom line, if you need accurate elapsed time calculations while an app is running, use CACurrentMediaTime. But if you're going to save this start time in persistent storage which you might recall when the app is restarted at some future date, then you have to use Date or CFAbsoluteTimeGetCurrent, 和 just live with any inaccuracies that may entail.

Swift相关问答推荐

macOS托盘应用程序中的列表显示奇怪

SwiftUI - NavigationLink(value:)和navigationDestination不工作

了解SWIFT中的任务行为

带DispatchSourceTimer的定时器

如何强制创建新的UIViewControllerRenatable|更新Make UIViewController上的视图

可以';t在标记为@Observable的类上使用属性包装

expose 不透明的底层类型

在 Swift 5.7 中使用协议作为类型时什么时候需要写 `any`

如何在 SwiftUI 中为过渡动画保持相同的标识

为什么我的 tableView 没有推送到 tableView 内的 detailViewController?

为什么在Swift中每次调用Decimal类型的formatted()方法都会越来越慢?

在 Select 器上显示alert Select SwiftUI

Xcode swift ui 错误KeyPathComparator仅在 macOS 12.0 或更高版本中可用

Swift 2.0 方法不能标记为@objc,因为参数的类型不能在 Objective-C 中表示

理解 Swift 2.2 Select 器语法 - #selector()

Swift - 获取本地日期和时间

iOS 判断应用程序是否可以访问麦克风

如何使用 Swift/iOS 为人类书写的笔画制作动画?

在 Swift 4 中,如何删除基于块的 KVO 观察者?

Swift 中的 CommonHMAC