最近在做APP時烈和,要使用短信動態(tài)碼來進(jìn)行系統(tǒng)認(rèn)證周拐,google了一下發(fā)現(xiàn)沒有成熟的實(shí)例铡俐,在github也找不到好的,基本都存在一點(diǎn)小問題妥粟,所以動手寫了一個审丘,
實(shí)現(xiàn)思路:
1.繼承自UIButton,初始化基本的屬性勾给;
2.利用Timer類計時方法滩报,每隔一秒執(zhí)行一次updateLabel方法
3.如果直對按鈕title進(jìn)行修改,會有多數(shù)文章提到的閃爍問題播急,在此使用一個Label覆蓋在Button上露泊,大小一致,解決此問題
效果如下:
實(shí)現(xiàn)代碼:
importUIKit
classO2CountdownButton:UIButton{
//定時秒數(shù)
varcount:Int=60
//定時器
vartimer:Timer!
//標(biāo)簽
varlabelTimeS:UILabel!
//默認(rèn)按鈕標(biāo)題
varnormalText ="獲取驗證碼"{
didSet{
self.setTitle(normalText, for: .normal)
self.layoutIfNeeded()
}
}
//標(biāo)簽字顏色
varlabelTextColor =UIColor.white
//按鈕正常背景色
varnormalColor =RGB(251, g:71, b:71) {
didSet{
ifself.isEnabled{
self.backgroundColor=normalColor
self.layoutIfNeeded()
}
}
}
//按鈕定時時的背景色
vardisableColor =toolbar_text_color{
didSet{
if!self.isEnabled{
self.backgroundColor=disableColor
self.layoutIfNeeded()
}
}
}
overridefuncawakeFromNib() {
super.awakeFromNib()
labelTimeS=UILabel(x:0, y:0, w:self.frame.size.width, h:self.frame.size.height)
labelTimeS.textAlignment= .center
labelTimeS.font=UIFont(name:"PingFangSC-Regular", size:14.0)!
labelTimeS.text=normalText
labelTimeS.textColor=labelTextColor
//self.addSubview(labelTimeS)
self.setTitle(normalText, for: .normal)
self.setTitleColor(UIColor.white, for: .normal)
self.backgroundColor=normalColor
}
publicfuncstartCount(){
self.isEnabled=false
//把按鈕本身標(biāo)題清空
self.setTitle("", for: .normal)
//開始把Label add Button
labelTimeS.text="\(self.count)s重新獲取"
self.addSubview(labelTimeS)
//設(shè)置按鈕背景色
self.backgroundColor=disableColor
iftimer!=nil{
timer.invalidate()
timer=nil
}
timer=Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(updateLabel), userInfo:nil, repeats:true)
timer.fire()
}
///停止更新
publicfuncstopCount(){
timer.invalidate()
labelTimeS.removeFromSuperview()
self.setTitle(normalText, for: .normal)
count=60
self.isEnabled=true
self.backgroundColor=normalColor
}
///每秒更新一次Label
@objcfileprivatefuncupdateLabel(){
count-=1;
ifcount<=0{
self.stopCount()
}else{
labelTimeS.text="\(self.count)s重新獲取"
}
}
}
源代碼鏈接:倒計時器按鈕