我正在嘗試做一個計時器計數up我按住一個按鈕的秒數(記錄一個視頻),它的工作不正常......有時它跳過秒&有時只是凍結,然後加快趕上...我真的需要你的幫助解決這個問題,我需要計時器是流體和恆定的,因爲它可以得到,謝謝。計時器不能正常工作,Swift
//Timer Variables:
var recordingCounter : Timer!
var minutes: Int = 0
var seconds: Int = 0
var counterString : String = ""
func longTap(_ sender: UIGestureRecognizer){
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
recordingCounter.invalidate()
seconds = 0
minutes = 0
if self.timerView.alpha == 1.0 {
UIView.animate(withDuration: 0.2, animations: {
self.timerView.alpha = 0.0
self.timerView.isHidden = true
self.recordingCounter.invalidate()
self.seconds = 0
self.minutes = 0
self.counterString = "00:00"
self.countingLabel.text = self.counterString
})
}
return
}else if sender.state == .began {
timerView.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.timerView.alpha = 1.0
})
print("UIGestureRecognizerStateBegan.")
recordingCounter = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
}
func updateCounter() {
seconds += 1
if seconds == 60 {
minutes += 1
seconds = 0
}
let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"
counterString = "\(minutesString):\(secondsString)"
countingLabel.text = counterString
}
順便說一句我跑我的自定義AVFoundation相機的VideoPreviewLayer在同一時間..可能導致的問題?
如果您需要精確的測量,請勿使用「定時器」。使用'CADisplayLink'。 –
嘗試在updateCounter方法中異步更新標籤。 –
@AllenHumphreys我該怎麼做? – RandomGeek