swift3.0-用GCD实现验证码倒计时效果

2017-07-12  本文已影响34人  唉哦诶斯

//获取验证码 @IBAction func getVerificationCode(_ sender: UIButton) { //先让按钮不能点 sender.isUserInteractionEnabled = false var time = 60 let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global()) //开始时间,时间间隔 timer.scheduleRepeating(wallDeadline: .now(), interval: 1) //每个时间段执行的方法 timer.setEventHandler { time -= 1 //回到主线程更新按钮标题 DispatchQueue.main.sync(execute: { sender.setTitle("\(time)s", for: .normal) }) //倒计时到0时,设置默认标题,打开用户交互,取消定时任务 if time == 0 { DispatchQueue.main.sync(execute: { sender.setTitle("验证", for: .normal) sender.isUserInteractionEnabled = true }) timer.cancel() } } //开启定时器 timer.resume() }

上一篇 下一篇

猜你喜欢

热点阅读