示例效果图
2019-03-20 11-01-39.2019-03-20 11_02_53.gif
// 封装倒计时button
class CountDownTimerButton: UIButton {
private var countdownTimer: Timer?
// 声明闭包,在外面使用时监听按钮的点击事件
typealias ClickedClosure = (_ sender: UIButton) -> Void
var clickedBlock: ClickedClosure?
override init(frame: CGRect) {
super.init(frame: frame)
setting_init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setting_init()
}
private func setting_init() {
self.setTitleColor(kBlue, for: .normal)
self.setTitle("获取验证码", for: .normal)
self.addTarget(self, action: #selector(sendButtonClick(_:)), for: .touchUpInside)
}
var remainingSeconds: Int = 5 {
willSet {
self.setTitle("\(newValue) s", for: .normal)
if newValue <= 0 {
self.setTitle("重新获取", for: .normal)
isCounting = false
}
}
}
var isCounting = false {
willSet {
// newValue 为true表示可以计时
if newValue {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTime(_:)), userInfo: nil, repeats: true)
} else {
countdownTimer?.invalidate()
countdownTimer = nil
}
// 设置按钮可用或不可用(按钮的isEnabled值与 newValue的值是相反的)
self.isEnabled = !newValue
}
}
// 按钮点击事件(在外面也可以再次定义点击事件,对这个不影响,会并为一个执行)
@objc func sendButtonClick(_ sender: UIButton) {
//将 isCounting 设置为true,表示可以从新计时
isCounting = true
if clickedBlock != nil {
self.clickedBlock!(sender)
}
}
@objc func updateTime(_ timer: Timer) {
remainingSeconds -= 1
}
}
网友评论