2017-08-05 157 views
2

我正在嘗試做一個計時器計數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在同一時間..可能導致的問題?

+0

如果您需要精確的測量,請勿使用「定時器」。使用'CADisplayLink'。 –

+0

嘗試在updateCounter方法中異步更新標籤。 –

+0

@AllenHumphreys我該怎麼做? – RandomGeek

回答

3

Timer作品在此相同DispatchQueue由於用戶交互(例如在UITableView滾動,抽頭在UIGestureRecognizer或保持在UIbutton)。所以當用戶做任何事情時,Timer會暫時凍結。

您可以通過使用例如AsyncTimer來解決此問題。

+0

技術上定時器[附加到運行循環](https://developer.apple.com/documentation/foundation/runloop/1418468-add)。運行循環驅動驅動調度隊列的線程。 –