先寫代碼包蓝,之后寫講解,最近有點忙
//發(fā)送驗證碼
@IBAction func sendCodeBtn(_ sender: Any) {
var codeNum = codeNumTF.text
//調(diào)用方法
self.countDown(timeOut: 5)
}
//驗證碼倒計時
func countDown(timeOut:Int){
//倒計時時間
var timeout = timeOut
let queue:DispatchQueue = DispatchQueue.global(qos: .default)
// 在global線程里創(chuàng)建一個時間源
let codeTimer = DispatchSource.makeTimerSource(queue:queue)
codeTimer.scheduleRepeating(deadline: .now(), interval:.seconds(1))
//每秒執(zhí)行
codeTimer.setEventHandler(handler: { () -> Void in
if(timeout<=0){ //倒計時結(jié)束双揪,關(guān)閉
codeTimer.cancel()
DispatchQueue.main.sync(execute: { () -> Void in
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
self.sendCode.setTitle("重新發(fā)送", for: UIControlState.normal)
self.sendCode.isUserInteractionEnabled = true
})
}else{//正在倒計時
let seconds = timeout
let strTime = NSString.localizedStringWithFormat("%.d", seconds)
DispatchQueue.main.sync(execute: { () -> Void in
// NSLog("----%@", NSString.localizedStringWithFormat("%@S", strTime) as String)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
self.sendCode.setTitle(NSString.localizedStringWithFormat("%@S", strTime) as String, for: UIControlState.normal)
UIView.commitAnimations()
self.sendCode.isUserInteractionEnabled = false
})
timeout -= 1;
}
})
codeTimer.resume()
}
}
貌似不用講解视事,太簡單了