【Swift3.0】iOS Swift 验证码按钮倒计时

定义变量

 
    public var timerVerify:Timer!
    public var verifyButton:UIButton!
    public let VERIFY_TIME_EXPIRY = 31
    public var timeCount:Int = 31

调用完成获取验证码接口后,启动计时器

    public func startVerifyTimer(){
//        self.verifyButton.titleLabel?.adjustsFontSizeToFitWidth = true
        refreshVerifyBtnDisplay()
        timerVerify = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(BaseViewController.refreshVerifyBtnDisplay), userInfo: nil, repeats: true)
    }
    

异步刷新页面按钮的文字

    public func refreshVerifyBtnDisplay(){
        UIView.performWithoutAnimation({
            timeCount = timeCount - 1
            if timeCount==0 {
                self.verifyButton.isEnabled = true
                self.verifyButton.backgroundColor = UIColor.colorWithHexString(hex: "#A80000")
                self.verifyButton.setTitle(String.init(format: "send.verify.code".localized()), for: .normal)
                self.timerVerify.invalidate()
                self.timerVerify = nil
                self.timeCount = VERIFY_TIME_EXPIRY
                self.verifyCode = ""
            }else{
                
                self.verifyButton.isEnabled = false
                self.verifyButton.backgroundColor = UIColor.colorWithHexString(hex: "#666666")
                self.verifyButton.setTitle(("send.verify.code".localized()+"("+String.init(timeCount)+")"), for: .normal)
                
            }
            self.verifyButton.layoutIfNeeded()
        })
        
    }

你可能感兴趣的:(【Swift3.0】iOS Swift 验证码按钮倒计时)