1、在global線程里創建一個時間源
// 在global線程里創建一個時間源
let codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
2、開始Dispatch Timer
// Dispatch Timer
fileprivate func startGCDTimer() {
// 設定這個時間源是每秒循環一次,立即開始
codeTimer.schedule(deadline: .now(), repeating: .seconds(1))
// 設定時間源的觸發事件
codeTimer.setEventHandler(handler: {
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
self.timerMethod()
}
})
// 判斷是否取消,如果已經取消了,調用resume()方法時就會崩潰?。?!
if codeTimer.isCancelled {
return
}
// 啟動時間源
codeTimer.resume()
}
3、時分秒之間的轉化
@objc fileprivate func timerMethod() {
// 秒
if sec >= 59 {
sec = 0
// 分鐘
if min >= 59 {
min = 0
// 時
hour = hour + 1
}else {
min = min + 1
}
// print("*****秒:\(sec), 分:\(min)")
}else {
sec = sec + 1
// print("時:\(hour), 分:\(min), 秒:\(sec)")
}
print("時:\(hour), 分:\(min), 秒:\(sec)")
textView.text = String(format: "%02d", hour) + "-" + String(format: "%02d", min) + "-" + String(format: "%02d", sec)
}
調用如下:
開始
@IBAction func clickedStartButton(_ sender: UIButton) {
startGCDTimer() // 開始
}
暫停
注:暫停之后,再點擊開始,是接著上次暫停進行的開始計時!!!
@IBAction func clickedStopButton(_ sender: UIButton) {
codeTimer.suspend() // 暫停
}
取消
取消后,再次點擊開始也是沒有計時的,因為取消代表的是結束計時,而不是暫停?。?!
@IBAction func clickedCancleButton(_ sender: UIButton) {
codeTimer.cancel() // 取消
}