初始化方法
let btn = CJSCountDownBtn(count: 5, frame: CGRect(x: 30, y: 30, width: 100, height: 50))
按钮其它属性可自行设置
// 按钮其他属性可自行设置
btn.setTitle("获取验证码", for: .normal)
btn.backgroundColor = UIColor.red
btn.setTitleColor(UIColor.black, for: .normal)
开启倒计时
// 按钮倒计时启动
btn.isCounting = true;
实现代码
import UIKit
class CJSCountDownBtn: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
便利构造器
- parameter count: 倒计时总时间
- parameter frame: 按钮frame
*/
convenience init(count: Int,frame: CGRect) {
self.init(frame: frame)
totalTime = count
remainingTime = count
addTarget(self, action: #selector(btnClick), for: UIControlEvents.touchUpInside)
}
/**
按钮内部响应事件
*/
@objc fileprivate func btnClick() {
// isCounting = true
}
/// 总时间
fileprivate var totalTime = 0
/// 剩余时间
fileprivate var remainingTime = 0
/// 定时器
fileprivate var countDownTimer: Timer?
/// 是否处于倒计时状态
var isCounting = false {
willSet {
if newValue {
isUserInteractionEnabled = false
countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
} else {
countDownTimer?.invalidate()
countDownTimer = nil
isUserInteractionEnabled = true
remainingTime = totalTime
}
}
}
/**
计时器响应方法
*/
@objc fileprivate func updateTime() {
remainingTime -= 1
if remainingTime > 0 {
setTitle("\(remainingTime)秒", for: UIControlState())
}else{
setTitle("重新获取", for: UIControlState())
isCounting = false
}
}
}