swift数字倒计时的简单实现

核心代码如下

//剩余的秒数
    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
        })
    }

这样就简单的实现了倒计时的功能。

你可能感兴趣的:(swift数字倒计时的简单实现)