import UIKit
class TwoViewController: UIViewController {
//获取验证码按钮
@IBOutlet var button1: UIButton!
//创建Timer计时器
var countdownTimer: Timer?
//创建属性观察器,属性改变之前调用(倒计时的值)
var remainingSeconds: Int = 0{
willSet{
//在按钮的普通状态下改变 按钮的标题(.normal:普通状态; .highlighted:触摸状态下的文字; .disabled:禁用状态下的文字)
button1.setTitle("(\(newValue)秒后重新获取)", for: .normal)
if newValue <= 0 {
button1.setTitle("重新获取验证码", for: .normal)
isCounting = false
}
}
}
//属性观察器,属性改变之前调用(该属性用于标识计时是结束还是开始;true:为开始计时;false:为结束计时)
var isCounting = false{
willSet{
if newValue{
//开始计时
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TwoViewController.updateTime(_:)), userInfo: nil, repeats: true)
//初始化值倒计时的值
remainingSeconds = 5;
//开始计时时设置按钮的背景颜色
button1.backgroundColor = UIColor.gray
}else{
//结束计时
countdownTimer?.invalidate()//关闭计时
countdownTimer = nil //将计时器Timer的执行函数滞空
button1.backgroundColor = UIColor.red//按钮背景色设置为红色
}
//设置按钮是否可点击(当计时开始的时候按钮不可点击,计时结束的时候按钮可以点击,所以取的是newValue的反值)
button1.isEnabled = !newValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
//设置按钮的监听事件
button1.addTarget(self, action: #selector(TwoViewController.sendButtonClick(_:)), for: .touchUpInside)
}
//创建按钮的点击的函数
@objc func sendButtonClick(_ sender: UIButton){
//设置计时开始
isCounting = true
}
//计时器每1秒执行的函数
@objc func updateTime(_ timer: Timer){
//每一秒减1
remainingSeconds -= 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
iOS-swift验证码倒计时(及属性观察器的使用)
最新推荐文章于 2025-05-21 12:22:10 发布