iOS-swift验证码倒计时(及属性观察器的使用)

本文介绍了一种使用Swift在iOS应用中实现验证码倒计时按钮的方法。通过创建Timer计时器并结合按钮状态更新,实现了按钮从点击到倒计时结束的整个流程。文章详细解释了代码中涉及的属性观察器、定时器设置及按钮事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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.
    }
    */

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值