// MARK: 显示时间label
private lazy var timeLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 20)
return label
}()
// MARK: GCD定时器
var timerS: DispatchSourceTimer?
//设定定时时间
var countTime: Int = 0
func setTimerWithGCD()
{
// 在global线程里创建一个时间源
self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 设定这个时间源是每1.0秒循环一次,立即开始
timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
// 设定时间源的触发事件
timerS?.setEventHandler(handler: {
// 每1秒计时一次
self.countTime += 1
// 返回主线程处理一些事件,更新UI等等
DispatchQueue.main.async {
self.setTimerStr()
}
})
//启动定时器
timerS?.activate()
}
var minute: Int = 0
// MARK: 将int转换成时间格式样式的方法
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
上面的是正序的时间,下面这个是倒叙的时间
// MARK: GCD定时器
var timerS: DispatchSourceTimer?
//设定定时时间
var countTime: Int = 60
func setTimerWithGCD()
{
// 在global线程里创建一个时间源
self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 设定这个时间源是每1.0秒循环一次,立即开始
timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
// 设定时间源的触发事件
timerS?.setEventHandler(handler: {
// 每1秒计时一次
self.countTime -= 1
// 返回主线程处理一些事件,更新UI等等
DispatchQueue.main.async {
self.setTimerStr()
}
})
//启动定时器
if #available(iOS 10.0, *) {
timerS?.activate()
} else {
timerS?.resume()
}
}
//表示倒计时总时间
var minute: Int = 14
// MARK: 将int转换成时间格式样式的方法
private func setTimerStr()
{
if minute <= 0 && countTime <= 0
{
print("时间结束")
self.timeLabel.text = "00: 00"
timerS?.cancel()
// 这里进行发服务,时间变成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))"
}