ios swift 短信验证码倒计时

    @IBOutlet var codeBtn: UIButton!
    @IBAction func codeBtnClick(_ sender: Any) {
        isCounting = true
    }
    
    var countdownTimer: Timer?
    
    var remainingSeconds: Int = 0 {
        willSet {
            codeBtn.setTitle("\(newValue)S", for: .normal)
            if newValue <= 0 {
                codeBtn.setTitle(NSLocalizedString("getCode", comment: ""), for: .normal)
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 6
                codeBtn.backgroundColor = UIColor.gray
            }else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                codeBtn.backgroundColor = UIColor.mainColor
            }
            codeBtn.isEnabled = !newValue
        }
    }
    
    @objc func updateTime() {
        remainingSeconds -= 1
    }

参考博客:
[iOS] 短信验证码倒计时Button的实现 (Swift)

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页