美文网首页
ios短信倒计时器按钮实例swift3.0版

ios短信倒计时器按钮实例swift3.0版

作者: 5210167 | 来源:发表于2016-12-16 17:17 被阅读61次

最近在做APP时,要使用短信动态码来进行系统认证,google了一下发现没有成熟的实例,在github也找不到好的,基本都存在一点小问题,所以动手写了一个,

实现思路:

1.继承自UIButton,初始化基本的属性;

2.利用Timer类计时方法,每隔一秒执行一次updateLabel方法

3.如果直对按钮title进行修改,会有多数文章提到的闪烁问题,在此使用一个Label覆盖在Button上,大小一致,解决此问题

效果如下:

实现代码:

importUIKit

classO2CountdownButton:UIButton{

//定时秒数

varcount:Int=60

//定时器

vartimer:Timer!

//标签

varlabelTimeS:UILabel!

//默认按钮标题

varnormalText ="获取验证码"{

didSet{

self.setTitle(normalText, for: .normal)

self.layoutIfNeeded()

}

}

//标签字颜色

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

//把按钮本身标题清空

self.setTitle("", for: .normal)

//开始把Label add Button

labelTimeS.text="\(self.count)s重新获取"

self.addSubview(labelTimeS)

//设置按钮背景色

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重新获取"

}

}

}

源代码链接:倒计时器按钮

相关文章

网友评论

      本文标题:ios短信倒计时器按钮实例swift3.0版

      本文链接:https://www.haomeiwen.com/subject/wknnmttx.html