先写代码,之后写讲解,最近有点忙
//发送验证码
@IBAction func sendCodeBtn(_ sender: Any) {
var codeNum = codeNumTF.text
//调用方法
self.countDown(timeOut: 5)
}
//验证码倒计时
func countDown(timeOut:Int){
//倒计时时间
var timeout = timeOut
let queue:DispatchQueue = DispatchQueue.global(qos: .default)
// 在global线程里创建一个时间源
let codeTimer = DispatchSource.makeTimerSource(queue:queue)
codeTimer.scheduleRepeating(deadline: .now(), interval:.seconds(1))
//每秒执行
codeTimer.setEventHandler(handler: { () -> Void in
if(timeout<=0){ //倒计时结束,关闭
codeTimer.cancel()
DispatchQueue.main.sync(execute: { () -> Void in
//设置界面的按钮显示 根据自己需求设置
self.sendCode.setTitle("重新发送", 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)
//设置界面的按钮显示 根据自己需求设置
self.sendCode.setTitle(NSString.localizedStringWithFormat("%@S", strTime) as String, for: UIControlState.normal)
UIView.commitAnimations()
self.sendCode.isUserInteractionEnabled = false
})
timeout -= 1;
}
})
codeTimer.resume()
}
}
貌似不用讲解,太简单了