2017-06-20 78 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,太棒了! –