// MARK: 顯示時(shí)間label
private lazy var timeLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 20)
return label
}()
// MARK: GCD定時(shí)器
var timerS: DispatchSourceTimer?
//設(shè)定定時(shí)時(shí)間
var countTime: Int = 0
func setTimerWithGCD()
{
// 在global線程里創(chuàng)建一個(gè)時(shí)間源
self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 設(shè)定這個(gè)時(shí)間源是每1.0秒循環(huán)一次,立即開始
timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
// 設(shè)定時(shí)間源的觸發(fā)事件
timerS?.setEventHandler(handler: {
// 每1秒計(jì)時(shí)一次
self.countTime += 1
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
self.setTimerStr()
}
})
//啟動(dòng)定時(shí)器
timerS?.activate()
}
var minute: Int = 0
// MARK: 將int轉(zhuǎn)換成時(shí)間格式樣式的方法
private func setTimerStr()
{
if minute == 59 {minute = 0}
if self.countTime > 59
{
self.countTime = 0
minute += 1
}
self.timeLabel.text = "\(String.init(format: "%02d", minute)) " + ": " + "\(String.init(format: "%02d", self.countTime))"
}

image.png
上面的是正序的時(shí)間,下面這個(gè)是倒敘的時(shí)間
// MARK: GCD定時(shí)器
var timerS: DispatchSourceTimer?
//設(shè)定定時(shí)時(shí)間
var countTime: Int = 60
func setTimerWithGCD()
{
// 在global線程里創(chuàng)建一個(gè)時(shí)間源
self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 設(shè)定這個(gè)時(shí)間源是每1.0秒循環(huán)一次,立即開始
timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
// 設(shè)定時(shí)間源的觸發(fā)事件
timerS?.setEventHandler(handler: {
// 每1秒計(jì)時(shí)一次
self.countTime -= 1
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
self.setTimerStr()
}
})
//啟動(dòng)定時(shí)器
if #available(iOS 10.0, *) {
timerS?.activate()
} else {
timerS?.resume()
}
}
//表示倒計(jì)時(shí)總時(shí)間
var minute: Int = 14
// MARK: 將int轉(zhuǎn)換成時(shí)間格式樣式的方法
private func setTimerStr()
{
if minute <= 0 && countTime <= 0
{
print("時(shí)間結(jié)束")
self.timeLabel.text = "00: 00"
timerS?.cancel()
// 這里進(jìn)行發(fā)服務(wù),時(shí)間變成00之后需要做的事情
return
}
if self.countTime < 0
{
self.countTime = 59
minute -= 1
}
self.timeLabel.text = "\(String.init(format: "%02d", minute)) " + ": " + "\(String.init(format: "%02d", self.countTime))"
}