核心代碼如下
//剩余的秒數
var remainingSeconds = 0{
//remainingSeconds發生改變時
willSet {
remindLabel?.setTitle("接收短信大約需要\(newValue)秒", for: .normal)
remindLabel?.isEnabled = false
//當remainingSeconds小于等于0時執行
if newValue <= 0 {
isCounting = false
remindLabel?.isEnabled = true
remindLabel?.setTitle("收不到驗證碼?", for: .normal)
remindLabel?.setTitleColor(MainColor, for: .normal)
}
}
}
//是否開始計時
var isCounting = false {
willSet {
//當isCounting為true時執行
if newValue {
let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
self.countdownTimer = timer
remainingSeconds = 59
} else {
countdownTimer?.invalidate()
countdownTimer = nil
}
}
}
func updateTime(){
remainingSeconds -= 1
}
實現流程大概是這樣的
isCounting發生改變-> timer開始執行 -> remainingSeconds發生改變 ->remainingSeconds willset執行 -> 當remainingSeconds小于等于0 -> isCounting = false -> timer停止
只要控制isCouning的值就可以實現倒計時的開關了,代碼中的remindLabel是顯示倒計時時間的label
退出到后臺需要這一段代碼配置一下
func applicationDidEnterBackground(_ application: UIApplication) {
//如果已存在后臺任務,先將其設為完成
if self.backgroundTask != nil {
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
//注冊后臺任務
self.backgroundTask = application.beginBackgroundTask(expirationHandler: {
() -> Void in
//如果沒有調用endBackgroundTask,時間耗盡時應用程序將被終止
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
})
}
這樣就簡單的實現了倒計時的功能。