仿了一个博主的计时器,他用oc写的,我用swift翻译了一遍。在这里给这个博主抱拳了!
这里是展示demo:
import UIKit
let DEFAULT_STARTTEXT = "获取验证码"
let DEFAULT_ENDTEXT = "重新获取"
class ZCodeButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setCodeButton()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setCodeButton()
// fatalError("init(coder:) has not been implemented")
}
var startText:String? = DEFAULT_STARTTEXT //开始提示
var endText:String? = DEFAULT_ENDTEXT //结束提示
//默认时间
var time:NSTimeInterval = 60 //默认60秒
//UI属性
var textFont:CGFloat = 13 //字体大小
var cornerRadius:CGFloat = 5 //弧度
var boardWitdh:CGFloat = 0 //外边框宽度
var boardColor:UIColor = UIColor.darkGrayColor() //边框颜色
var startBackColor = UIColor.lightGrayColor() //起始颜色
var endBackColor = UIColor.darkGrayColor() //结束颜色
var startTextColor:UIColor = UIColor.whiteColor() //起始字体颜色
var endTextColor:UIColor = UIColor.whiteColor() //结束字体颜色
//私有属性
var indexTime:NSTimeInterval = 60
//初始化设置CodeButton
func setCodeButton(){
self.layer.borderColor = self.boardColor.CGColor
self.layer.borderWidth = self.boardWitdh
self.layer.masksToBounds = true
self.layer.cornerRadius = self.cornerRadius
self.setTitle(self.startText, forState: UIControlState.Normal)
self.setTitleColor(startTextColor, forState: UIControlState.Normal)
self.titleLabel?.font = UIFont.systemFontOfSize(13)
self.backgroundColor = BUTTON_COLOR
self.indexTime = time
}
func start(){
self.titleLabel!.transform = CGAffineTransformMakeScale(0.9, 0.9);
self.titleLabel!.alpha = 1
self.setTitleColor(startBackColor, forState: UIControlState.Normal)
self.setTitleColor(endTextColor, forState: UIControlState.Disabled)
self.backgroundColor = startBackColor
self.enabled = false
if indexTime > 0{
weak var weakSelf = self
self.setTitle("\(Int(weakSelf!.indexTime))秒", forState: UIControlState.Normal)
self.setTitle("\(Int(weakSelf!.indexTime))秒", forState: UIControlState.Disabled)
UIView.animateWithDuration(1, animations: { () -> Void in
self.titleLabel!.transform = CGAffineTransformMakeScale(1, 1)
self.titleLabel!.alpha = 0
}, completion: { (completion) -> Void in
if weakSelf != nil{
--weakSelf!.indexTime
weakSelf!.start()
}else{
weakSelf?.removeFromSuperview()
}
})
}else{
indexTime = time
self.enabled = true
self.setTitle(self.endText, forState: UIControlState.Normal)
self.setTitleColor(endTextColor, forState: UIControlState.Normal)
self.backgroundColor = BUTTON_COLOR
}
}
}
用的时候直接调用start()
方法就可以了。
有什么不懂的可以留言给我。也谢谢各位大神指导