
Snip20171225_4.png
代碼在這
// 定義需要計時的時間
var timeCount = 60
// 在global線程里創(chuàng)建一個時間源
let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 設(shè)定這個時間源是每秒循環(huán)一次,立即開始
codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
// 設(shè)定時間源的觸發(fā)事件
codeTimer.setEventHandler(handler: {
// 每秒計時一次
timeCount = timeCount - 1
// 時間到了取消時間源
if timeCount <= 0 {
codeTimer.cancel()
}
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
sender.setTitle("\(timeCount)s", for: UIControlState.normal)
}
})
// 啟動時間源
codeTimer.resume()
}
簡單使用

Untit.gif
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(composeBtn)
composeBtn.frame = CGRect(x: 100, y: 100, width: 150, height: 40)
}
fileprivate lazy var composeBtn:UIButton = {
let btn = UIButton()
btn.backgroundColor = UIColor.red
btn.setTitle("獲取驗(yàn)證碼", for: UIControlState.normal)
btn.addTarget(self, action: #selector(btnClick(sender:)), for: UIControlEvents.touchUpInside)
return btn
}()
func btnClick(sender:UIButton) {
// Do any additional setup after loading the view, typically from a nib.
// 定義需要計時的時間
var timeCount = 60
// 在global線程里創(chuàng)建一個時間源
let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 設(shè)定這個時間源是每秒循環(huán)一次,立即開始
codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
// 設(shè)定時間源的觸發(fā)事件
codeTimer.setEventHandler(handler: {
// 每秒計時一次
timeCount = timeCount - 1
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
sender.isEnabled = false
sender.backgroundColor = UIColor.lightGray
sender.setTitle("\(timeCount)s", for: UIControlState.normal)
}
// 時間到了取消時間源
if timeCount <= 0 {
DispatchQueue.main.async {
sender.isEnabled = true
sender.backgroundColor = UIColor.red
sender.setTitle("重新獲取驗(yàn)證碼", for: UIControlState.normal)
}
codeTimer.cancel()
}
})
// 啟動時間源
codeTimer.resume()
}