Swift做倒计时,获取验证码功能

首先创建一个计时器 NSTimer:

private var timer: NSTimer?

创建一个Bool值 , 表示是否开始计时:

private var isCounting: Bool = false {//是否开始计时
        willSet(newValue) {
            if newValue {
                timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(MRegisterViewController.updateTimer), userInfo: nil, repeats: true)
            } else {
                timer?.invalidate()
                timer = nil
            }
        }
    }

var一个当前倒计时剩余的秒数:

private var remainingSeconds: Int = 0 {//remainingSeconds数值改变时 江将会调用willSet方法
        willSet(newSeconds) {
            let seconds = newSeconds%60
            getCodeBtn.setTitle(NSString(format: "%02ds", seconds) as String, forState: UIControlState.Normal)
        }
    }//当前倒计时剩余的秒数

更新倒计时时间:

func updateTimer(timer: NSTimer) {// 更新时间
        if remainingSeconds > 0 {
            remainingSeconds -= 1
        }
        
        if remainingSeconds == 0 {
            getCodeBtn.setTitle("获取验证码", forState: UIControlState.Normal)
            getCodeBtn.enabled = true
            isCounting = !isCounting
            timer.invalidate()
        }
    }

获取验证码按钮点击事件:

self.remainingSeconds = 59
                    self.isCounting = !self.isCounting
                

代码逻辑: 首先isCounting为false, 并没有开始计时, 当我点击按钮时,isCounting为true, 这时isCounting被赋予了新的值,会执行willSet方法,从而执行了updateTime方法,在updateTime方法中,我们让remainingSeconds每秒减1,当remainingSeconds值改变时,会调用willSet方法,并将新的值显示在按钮上,当remainingSeconds减为0时,让按钮重新显示获取验证码字样,并结束倒计时,这样就实现了一个获取验证码倒计时的功能。

你可能感兴趣的:(Swift做倒计时,获取验证码功能)