swift 4.0 驗證碼按鈕倒計時

根據(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.lxweimin.com/p/87dc0b864898此文章基礎(chǔ)上進(jìn)行優(yōu)化,

若有不足請大家指出,虛心接受。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容