我正在使用Xcode與swift 3做一個基本的計時器。我有一個計時器標籤連接到我的視圖控制器,每秒更新標籤。當計時時間較長時,秒數增加得更快(請參閱GIF)。Swift3 scheduledTime seconds運行速度太快,當時間更長
任何人都可以解釋我做錯了什麼,或者我不應該做什麼(錯誤的方法,更好的功能)?
這是相關代碼:
@IBAction func startButtonTabbed(_ sender: UIButton) {
if (sender == startButton) {
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
start_time = formatter.string(from:now)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerAction), userInfo: nil, repeats: true)
} else {
timer.invalidate()
}
}
func timerAction() {
time += 1;
updateTimingLabel(seconds: time)
}
func updateTimingLabel(seconds: Int) {
self.timerLabel.text = stringFromTimeInterval(interval: TimeInterval(time)) as String
}
func stringFromTimeInterval(interval: TimeInterval) -> NSString {
let ti = NSInteger(interval)
let seconds = ti % 60
let minutes = (ti/60) % 60
let hours = (ti/3600)
return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)
}
這是發生了什麼:
@Ivan Skrobot的回答是正確的。我只是在測試項目中複製並粘貼你的代碼,並可以在按鈕上重複點擊兩次。點擊一次正確計數。就像你點擊按鈕一樣,它變得越來越快 – GIJOW