swift 4.0 验证码按钮倒计时

根据网上的方法优化完善了一下。button样式如字体颜色、背景色没做说明,自行按需修改。


1:创建一个计时器

private var timer:Timer? //计时器


2:创建是否开始计时的Bool值

private var isCounting:Bool=false{ //是否开始计时

willSet(newValue) {

if newValue {

timer=Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(updateTimer(timer:)), userInfo:nil, repeats:true)

}else{

timer?.invalidate()

timer=nil

}

}

}


3:当前剩余秒数

private var remainingSeconds:Int=0{ //remainingSeconds数值改变时 江将会调用willSet方法

willSet(newSeconds) {

let seconds = newSeconds%60

sendVerifyCodeBtn.setTitle(NSString(format:"%02ds", seconds)asString, for:UIControlState.normal)

}

}//当前倒计时剩余的秒数


4:给发送验证码按钮添加点击事件

sendVerifyCodeBtn.addTarget(self, action:#selector(sendVerifyCode), for:UIControlEvents.touchUpInside)//添加验证码按钮点击事件


5:启动倒计时与时间更新的方法,在此写 倒计时期间 与 倒计时结束后 按钮的样式

//倒计时更新时间方法

@objc func updateTimer(timer:Timer) {

// 启动倒计时

//isCounting = true

ifremainingSeconds>0{

remainingSeconds-=1

sendVerifyCodeBtn.isEnabled=false

//sendVerifyCodeBtn.setTitle("重新获取", for: UIControlState.normal)

}

if remainingSeconds == 0 {

sendVerifyCodeBtn.setTitle ("重新获取", for:UIControlState.normal)

sendVerifyCodeBtn.isEnabled=true

isCounting = ! isCounting

timer.invalidate()

}

}


6:实现发送验证码按钮点击事件


//发送验证码按钮点击事件

@objc func sendVerifyCode() {

self.remainingSeconds=59

self.isCounting= !self.isCounting

}


如过不喜欢button计时时一闪一闪的效果,将button的type改为custom即可


注:文章在www.jianshu.com/p/87dc0b864898此文章基础上进行优化,

若有不足请大家指出,虚心接受。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容