ios-swift-使用纯代码方式自定义验证吗倒计时按钮

//
//  DownTimer.swift
//  H56580E2E
//  自定义倒计时按钮
//

import UIKit

class DownTimerButton: UIButton {
    //倒计时器
    var countdownTimer: Timer?
//    //声明闭包,在外面使用时监听按钮的点击事件
//    typealias clickAlertClosure = (_ index: Int) -> Void

    override init(frame: CGRect) {
        super.init(frame: frame)
        setting_init()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setting_init()
    }

    func setting_init(){
        // 给开始按钮设置圆角
        self.layer.cornerRadius = 15.0
        self.setTitleColor(UIColor.white, for: .normal)
        self.backgroundColor = UIColor.blue
        self.setTitle("获取验证码", for: .normal)
        //设置监听事件
        self.addTarget(self, action: #selector(self.sendButtonClick(_:)), for: .touchUpInside)
    }

    //设置属性观察器
    var remainingSeconds: Int = 0{
        //属性值改变之前调用
        willSet{
           self.setTitle("\(newValue)秒后重新获取", 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)
                //设置计时的秒数
                remainingSeconds = 5
                //改变按钮的背景色
                self.backgroundColor = UIColor.gray
            }else{
               //关闭计时
                countdownTimer?.invalidate()
                //将其滞空
                countdownTimer = nil
                //按钮的背景色设置为蓝色
                self.backgroundColor = UIColor.blue
            }
            //设置按钮可用或不可用(按钮的isEnabled值与 newValue的值是相反的)
            self.isEnabled = !newValue
        }
    }

    //按钮点击事件(在外面也可以再次定义点击事件,对这个不影响,会并为一个执行)
    @objc func sendButtonClick(_ sender: UIButton){
        //将 isCounting 设置为true,表示可以从新计时
        isCounting = true
    }

    //更改计时
    @objc func updateTime(_ timer: Timer){
        remainingSeconds -= 1
    }
}

使用
这里写图片描述

猜你喜欢

转载自blog.csdn.net/wa172126691/article/details/80341394