前言:本篇文章在于记录常用的倒计时,方便查找。可以随时的,进行记忆
目录:
一、效果图
二、代码示例
三、主要逻辑
效果图展示:
代码示例
import UIKit // 封装倒计时button class CountDownTimerButton: UIButton { // 向外部提供可点击接口 // 声明闭包,在外面使用时监听按钮的点击事件 typealias ClickedClosure = (_ sender: UIButton) -> Void // 作为此类的属性 var clickedBlock: ClickedClosure? /// 计时器 private var countdownTimer: Timer? /// 计时器是否开启(定时器开启的时机) var isCounting = false { willSet { // newValue 为true表示可以计时 if newValue { countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime(_:)), userInfo: nil, repeats: true) } else { // 定时器停止时,定时器关闭时(销毁定时器) countdownTimer?.invalidate() countdownTimer = nil } // 判断按钮的禁用状态 有新值 按钮禁用 无新值按钮不禁用 self.isEnabled = !newValue } } /// 剩余多少秒 var remainingSeconds: Int = 5 { willSet { self.setTitle("\(newValue) s", for: .normal) if newValue <= 0 { self.setTitle("重新获取", for: .normal) isCounting = false } } } override init(frame: CGRect) { super.init(frame: frame) // 初始化 self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 配置UI func setupUI() -> Void { self.setTitle(" 获取验证码 ", for:.normal) self.setTitleColor(RGBAlpa(0,0,0,1), for: .normal) self.titleLabel?.font = UIFont.systemFont(ofSize: 13~) self.backgroundColor = UIColor.white self.layer.cornerRadius = 12~ self.layer.masksToBounds = true self.layer.borderWidth = 1.0 self.layer.borderColor = UIColor.black.cgColor self.addTarget(self, action: #selector(sendButtonClick(_:)), for: .touchUpInside) } // MARK: 点击获取验证码 // 按钮点击事件(在外面也可以再次定义点击事件,对这个不影响,会并为一个执行) @objc func sendButtonClick(_ btn:UIButton) { // 开启计时器 self.isCounting = true // 设置重新获取秒数 self.remainingSeconds = 60 // 调用闭包 if clickedBlock != nil { self.clickedBlock!(btn) } } // 开启定时器走的方法 @objc func updateTime(_ btn:UIButton) { remainingSeconds -= 1 } }
主要逻辑:
初始时isCounting为false, 表示没有开始计时
当我点击按钮时,isCounting为true, 开始计时,这时isCounting被赋予了新的值,会执行willSet方法,从而执行了updateTime方法,在updateTime方法中,我们让remainingSeconds每秒减1,当remainingSeconds值改变时,会调用willSet方法,并将新的值显示在按钮上。
当remainingSeconds减为0时,让按钮重新显示获取验证码字样,并结束倒计时,这样就实现了一个获取验证码倒计时的功能。
网友评论