swift3.0--Button获取验证码(带进度)

之前在cocoaChina还是哪看到一个OC版的(具体忘记了,时间有点久了,最近在自学swift,这个小Demo拿来练手,也算是记录,今后自己需要,找起来也方便。如有侵权,请留言联系)

带进度按钮实现代码如下(Demo就不留下了,所有代码都已贴上)
import UIKit

class CountDownView: UIView {
// MARK:- 属性定义
    var startBack: (() -> ())?
    var completeBack: (() -> ())?
    var progressLineWidth: CGFloat?
    var progressLineColor: UIColor?
    var countLb: UILabel?
    var totalTimes: NSInteger = 0
    var isCountDown:Bool = false
    
// MARK:- 懒加载
    fileprivate lazy var progressLayer:CAShapeLayer = {
        let progress = CAShapeLayer()
        let kWidth = self.frame.size.width
        let kHeight = self.frame.size.height
        progress.frame = CGRect(x: 0, y: 0, width: kWidth, height: kHeight)
        progress.position = CGPoint(x: kWidth/2.0, y: kHeight/2.0)
        let point = CGPoint(x: kWidth/2.0, y: kHeight/2.0)
        progress.path = UIBezierPath(arcCenter: point, radius: (kWidth - self.progressLineWidth!)/2.0, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true).cgPath
        progress.fillColor = UIColor.clear.cgColor
        progress.lineWidth = self.progressLineWidth!
        progress.strokeColor = self.progressLineColor!.cgColor
        progress.strokeEnd = 0
        progress.strokeStart = 0
        progress.lineCap = kCALineCapRound
        return progress
    }()
    
    fileprivate lazy var rotateAnimation:CABasicAnimation = {
        let rotateAnima = CABasicAnimation(keyPath: "transform.rotation.z")
        rotateAnima.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
        rotateAnima.fromValue = CGFloat(2 * M_PI)
        rotateAnima.toValue = CGFloat(0)
        rotateAnima.duration = CFTimeInterval(self.totalTimes)
        rotateAnima.isRemovedOnCompletion = false
        return rotateAnima
    }()
    
    fileprivate lazy var strokeAnimationEnd:CABasicAnimation = {
        let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd")
        strokeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
        strokeAnimation.duration = CFTimeInterval(self.totalTimes)
        strokeAnimation.fromValue = CGFloat(1)
        strokeAnimation.toValue = CGFloat(0)
        strokeAnimation.speed = Float(1.0)
        strokeAnimation.isRemovedOnCompletion = false
        return strokeAnimation
    }()
    
    fileprivate lazy var animationGroup:CAAnimationGroup = {
        let group = CAAnimationGroup()
        group.animations = [self.strokeAnimationEnd, self.rotateAnimation]
        group.duration = CFTimeInterval(self.totalTimes)
        return group
    }()
    
    /**
     *  初始化定时器
     frame         位置
     totalTime     总时间
     lineWidth     线宽
     lineColor     线色
     fontSize      字体大小(控件的宽度/多少)
     startFinishCallback    开始闭包
     completeFinishCallback 完成闭包
     */
    init(frame: CGRect, totalTime: NSInteger, lineWidth:CGFloat, lineColor:UIColor, textFontSize:CGFloat, startFinishCallback:@escaping () -> (), completeFinishCallback:@escaping () -> ()) {
        super.init(frame: frame)
        startBack = startFinishCallback
        completeBack = completeFinishCallback
        progressLineWidth = lineWidth
        progressLineColor = lineColor
        totalTimes = totalTime
        layer.addSublayer(progressLayer)
        createLabel(textFontSize: textFontSize)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK:- 逻辑处理
extension CountDownView {
    
    /** 创建label */
    fileprivate func createLabel(textFontSize: CGFloat) {
        let label = UILabel()
        label.frame = self.bounds
        label.textColor = self.progressLineColor
        label.font = UIFont.systemFont(ofSize: self.frame.size.width / textFontSize)
        label.textAlignment = .center
        addSubview(label)
        countLb = label
    }
    
    /** 创建定时器 */
    fileprivate func createTimer() {
        weak var weakSelf = self
        if totalTimes > 0 {
            var timeout = totalTimes
            // 1、获取一个全局队列
            let queue = DispatchQueue.global()
            // 2、创建间隔定时器
            let time = DispatchSource.makeTimerSource(flags: [], queue: queue)
            time.scheduleRepeating(deadline: .now(), interval: .seconds(1), leeway: .microseconds(100))
            time.setEventHandler(handler: {
                if timeout <= 0 {
                    // 2.1定时器取消
                    time.cancel()
                    // 2.2主线程刷新UI
                    DispatchQueue.main.async(execute: {
                        weakSelf?.isCountDown = false
                        weakSelf?.isHidden = true
                        weakSelf?.stopCountDown()
                    })
                }else {
                    weakSelf?.isCountDown = true
                    let seconds = timeout % 60
                    DispatchQueue.main.async(execute: { 
                        self.countLb?.text = "\(String(seconds))s"
                    })
                    timeout -= 1
                }
            })
            // 3、复原定时器
            time.resume()
        }
    }
    
    /** 开始倒计时 */
    func startTheCountDown(){
        self.isHidden = false
        isCountDown = true
        if (startBack != nil) {
            startBack!()
        }
        createTimer()
        progressLayer.add(animationGroup, forKey: "group")
    }
    
    /** 停止倒计时 */
    fileprivate func stopCountDown(){
        progressLayer.removeAllAnimations()
        if completeBack != nil {
            completeBack!()
        }
    }
}
VC中调用(PS:其中运用到了PKHUD,如需使用,请cocoapods自行添加)
import UIKit
import PKHUD
/** 倒计时总时间 */
private let kCountdownTime:Int = 8
/** 线宽 */
private let kLineWidth:CGFloat = 2.0
class ViewController: UIViewController {
    
    /** 带进度按钮计时器 */
    var countView: CountDownView?
    /** 普通按钮计时器 */
    fileprivate lazy var normalButton:UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        button.layer.cornerRadius = 5
        button.layer.shadowOffset = CGSize(width: 5, height: 5)
        button.layer.shadowOpacity = 0.8
        button.layer.shadowColor = UIColor.black.cgColor
        button.frame = CGRect(x: (self.view.frame.size.width - 200) / 2.0, y: 200, width: 200, height: 40)
        button.backgroundColor = UIColor.purple
        button.setTitle("获取验证码", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.addTarget(self, action: #selector(normalButtonClick), for: .touchUpInside)
        return button
    }()
    /** 剩余时间 */
    var remainingTime: Int = 0{
        willSet{
            normalButton.setTitle("\(newValue)s后重新获取", for: .normal)
            if newValue <= 0 {
                normalButton.setTitle("重新获取", for: .normal)
                isCounting = false
            }
        }
    }
    /** 计时器 */
    var timer: Timer?
    /** 按钮开关 */
    var isCounting:Bool = false {
        willSet {
            if newValue {
                /** 初始化计时器 */
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingTime = kCountdownTime
                normalButton.backgroundColor = UIColor.gray
            }else {
                // 暂停且销毁计时器
                timer?.invalidate()
                timer = nil
                normalButton.backgroundColor = UIColor.red
            }
            normalButton.isEnabled = !newValue
        }
    }

// MARK:- 系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
}

// MARK:- 设置UI
extension ViewController {
    
    fileprivate func setupUI() {
        view.backgroundColor = UIColor.white
        view.addSubview(normalButton)
        
        let progressBut = UIButton()
        progressBut.frame = CGRect(x: (view.frame.size.width - 200) / 2.0, y: 400, width: 200, height: 40)
        progressBut.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        progressBut.setTitle("获取验证码", for: .normal)
        progressBut.layer.cornerRadius = 5
        progressBut.layer.shadowOpacity = 0.7
        progressBut.layer.shadowColor = UIColor.black.cgColor
        progressBut.layer.shadowOffset = CGSize(width: 5, height: 5)
        progressBut.backgroundColor = UIColor.red
        progressBut.setTitleColor(UIColor.white, for: .normal)
        progressBut.addTarget(self, action: #selector(progressButtonCilck), for: .touchUpInside)
        view.addSubview(progressBut)
        
        let viewFrame = CGRect(x: (view.frame.size.width - 20) / 2.0, y: 400, width: 30, height: 30)
        let countDownView = CountDownView(frame: viewFrame, totalTime: kCountdownTime, lineWidth: kLineWidth, lineColor: UIColor.red, textFontSize: 2, startFinishCallback: {
            progressBut.isHidden = true
            
            }, completeFinishCallback: {
                progressBut.isHidden = false
                progressBut.setTitle("重新获取", for: .normal)
        })
        view.addSubview(countDownView)
        countView = countDownView
    }
}

// MARK:- 事件处理
extension ViewController {

    func normalButtonClick(){
        HUD.flash(.labeledSuccess(title: "", subtitle: "发送成功,请注意查收"), delay: 1.0)
        isCounting = true
    }
    
    func updateTime(timer: Timer){
        remainingTime -= 1
    }
//--------------------分割线-----------------------//
    
    func progressButtonCilck(){
        HUD.flash(.labeledSuccess(title: "", subtitle: "发送成功,请注意查收"), delay: 1.0)
        countView?.startTheCountDown()
    }
}
总结:

普通的按钮计时就不讲了,就是运用属性监听器:willSet(在新的值在改变之前调用)。带进度条的按钮逻辑理顺之后还是比较简单的,主要利用 闭包控制显示隐藏 + 动画组合 + 间隔定时器 来实现(在实现“** createTimer**”方法时候,费了我一点时间,swift3.0在此改动有点大,主要还是基础不扎实)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容