通過extension(擴展),簡單實現(xiàn)倒計時功能,有需要的可以參考下.
新建一個UIButton的擴展類,<small>UIButton-Extension.swift</small> 以下是代碼塊,只需要傳入倒計時的時間即可
// MARK: - 倒計時
extension UIButton{
public func countDown(count: Int){
// 倒計時開始,禁止點擊事件
isEnabled = false
// 保存當前的背景顏色
let defaultColor = self.backgroundColor
// 設置倒計時,按鈕背景顏色
backgroundColor = UIColor.gray
var remainingCount: Int = count {
willSet {
setTitle("重新發(fā)送(\(newValue))", for: .normal)
if newValue <= 0 {
setTitle("發(fā)送驗證碼", for: .normal)
}
}
}
// 在global線程里創(chuàng)建一個時間源
let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
// 設定這個時間源是每秒循環(huán)一次,立即開始
codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
// 設定時間源的觸發(fā)事件
codeTimer.setEventHandler(handler: {
// 返回主線程處理一些事件,更新UI等等
DispatchQueue.main.async {
// 每秒計時一次
remainingCount -= 1
// 時間到了取消時間源
if remainingCount <= 0 {
self.backgroundColor = defaultColor
self.isEnabled = true
codeTimer.cancel()
}
}
})
// 啟動時間源
codeTimer.resume()
}
}
以上,END!喜歡就點個贊唄!