在項目開發中經常需要用到倒計時的功能,比如注冊部分獲取驗證碼時,這里通過extension(UIButton)的方式來實現倒計時的功能
直接上代碼
var codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
extension UIButton {
//倒計時啟動
func countDown(count: Int){
// 倒計時開始,禁止點擊事件
isEnabled = false
var remainingCount: Int = count {
willSet {
setTitle("\(newValue)秒重發", for: .normal)
if newValue <= 0 {
setTitle("獲取驗證碼", for: .normal)
}
}
}
if codeTimer.isCancelled {
codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
}
// 設定這個時間源是每秒循環一次,立即開始
codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
// 設定時間源的觸發事件
codeTimer.setEventHandler(handler: {
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
// 每秒計時一次
remainingCount -= 1
// 時間到了取消時間源
if remainingCount <= 0 {
self.isEnabled = true
codeTimer.cancel()
}
}
})
// 啟動時間源
codeTimer.resume()
}
//取消倒計時
func countdownCancel() {
if !codeTimer.isCancelled {
codeTimer.cancel()
}
// 返回主線程
DispatchQueue.main.async {
self.isEnabled = true
if self.titleLabel?.text?.count != 0
{
self.setTitle("獲取驗證碼", for: .normal)
}
}
}
}
在需要的地方直接調用即可
//啟動倒計時
self.smsCodeBtn.countDown(count: 60)
//取消倒計時
self.smsCodeBtn.countdownCancel()