根據(jù)網(wǎng)上的方法優(yōu)化完善了一下添忘。button樣式如字體顏色参淹、背景色沒做說明媒役,自行按需修改暴备。
1:創(chuàng)建一個計時器
private var timer:Timer? //計時器
2:創(chuàng)建是否開始計時的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:當(dāng)前剩余秒數(shù)
private var remainingSeconds:Int=0{ //remainingSeconds數(shù)值改變時 江將會調(diào)用willSet方法
willSet(newSeconds) {
let seconds = newSeconds%60
sendVerifyCodeBtn.setTitle(NSString(format:"%02ds", seconds)asString, for:UIControlState.normal)
}
}//當(dāng)前倒計時剩余的秒數(shù)
4:給發(fā)送驗證碼按鈕添加點擊事件
sendVerifyCodeBtn.addTarget(self, action:#selector(sendVerifyCode), for:UIControlEvents.touchUpInside)//添加驗證碼按鈕點擊事件
5:啟動倒計時與時間更新的方法,在此寫 倒計時期間 與 倒計時結(jié)束后 按鈕的樣式
//倒計時更新時間方法
@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:實現(xiàn)發(fā)送驗證碼按鈕點擊事件
//發(fā)送驗證碼按鈕點擊事件
@objc func sendVerifyCode() {
self.remainingSeconds=59
self.isCounting= !self.isCounting
}
如過不喜歡button計時時一閃一閃的效果锨阿,將button的type改為custom即可
注:文章在www.reibang.com/p/87dc0b864898此文章基礎(chǔ)上進(jìn)行優(yōu)化宵睦,
若有不足請大家指出,虛心接受墅诡。