Swift实现iOS应用中短信验证码倒计时功能的实例分享

2020-01-15 14:49:35刘景俊

        sendButton.setTitle("验证码已发送((newValue)秒后重新获取)", forState: .Normal)

 

        if newValue <= 0 {
            sendButton.setTitle("重新获取验证码", forState: .Normal)
            isCounting = false
        }
    }
}


当remainingSeconds变化时更新sendButton的显示文本。

 

倒计时的功能我们用NSTimer实现,先声明一个NSTimer实例:

复制代码
var countdownTimer: NSTimer?
然后我们声明一个变量来开启和关闭倒计时:
复制代码
var isCounting = false {
    willSet {
        if newValue {
            countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTime", userInfo: nil, repeats: true)

 

            remainingSeconds = 10
            sendButton.backgroundColor = UIColor.grayColor()
        } else {
            countdownTimer?.invalidate()
            countdownTimer = nil

            sendButton.backgroundColor = UIColor.redColor()
        }

        sendButton.enabled = !newValue
    }
}


同样,我们给isCounting添加一个willSet方法,当isCounting的newValue为true时,我们通过调用NSTimer的类方法
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:创建并启动刚才声明的countdownTimer实例,这个实例每一秒钟调用一次updateTime:方法:
复制代码
func updateTime(timer: NSTimer) {
     // 计时开始时,逐秒减少remainingSeconds的值
    remainingSeconds -= 1
}
当isCounting的newValue为false时,我们停止countdownTimer并将countdownTimer设置为nil。