2017-06-20 80 views
0

我正在尝试确定用户触摸屏幕的确切时间。 我想出了这个(我的ViewController内):确定两次触摸之间的确切时间

var startTime: Date? 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    startTime = Date() 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    let endTime = Date() 
    print(endTime.timeIntervalSince(startTime!)) 
} 

似乎工作得很好。
这是否如此精确? 有没有办法测试这是多么精确?

+1

首先,你的标题是有点混乱。请调整!那么,要测试它,你要么尝试衡量时间。否则或者你需要有第二种方法可以做到这一点。但正如我所看到的那样,当你想从触摸的开始到结束测量总体时间时,这应该是最好的方式。但是不是使用'Date',你怎么看待[UITouch的时间戳](https://developer.apple.com/documentation/uikit/uitouch/1618144-timestamp)? –

回答

1

我会去做与你做的相同的结构。您的print(endTime.timeIntervalSince(startTime!))将为您打印出精确的Double价值。

我会调整它有点虽然,检查意见进行解释:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    startTime = Date() 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    // Don´t use startTime!, use if let instead 
    if let startTime = startTime { 
     // Use 2 decimals on your difference, or 3, or whatever suits your needs best 
     let difference = String(format: "%.2f", Date().timeIntervalSince(startTime)) 
     print(difference) 
    } 
} 
+0

我发现这个工作很好。与@Marcel T关于使用UITouches时间戳以获得更高精度的评论一起。 – Marmelador

+0

@Marmelador,太棒了! –