Swift_技巧(4)_GCD倒计时实现(swift3.0)

一丶

没什么好说的.swift3.0

Paste_Image.png
Paste_Image.png

二丶代码


//
//  UIButton+CountDown.swift
//  YQL
//
//  Created by xzb on 2017/7/28.
//  Copyright © 2017年 huazhiying. All rights reserved.
//

import Foundation
import UIKit


enum CountDownType : Int {
    case captcha  = 0
}

extension UIButton{
    
    
    fileprivate struct AssociatedKeys {
        static var timer: DispatchSourceTimer? = nil
    }
    
    fileprivate var timer:DispatchSourceTimer? {
        get {
            guard let timer = objc_getAssociatedObject(self, &AssociatedKeys.timer) as? DispatchSourceTimer else {
                return nil
            }
            return timer
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.timer, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func YQL_countDown(type:CountDownType,timeOut:UInt){
        var timeout  = timeOut
        if timeout != 0 {
            
            self.timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
            
            self.timer?.scheduleRepeating(wallDeadline: DispatchWallTime.now(), interval: .seconds(1))
            self.timer?.setEventHandler(handler: {
                
                if timeout <= 0 {
                    
                    DispatchQueue.main.async(execute: {
                        if type ==  .captcha{
                            self.setTitle("发送验证码", for: UIControlState.normal)
                            self.isEnabled = true
                            self.isUserInteractionEnabled = true
                        }
                    })
                } else {
                    DispatchQueue.main.async(execute: {
                        if type ==  .captcha{
                            self.titleLabel?.text = "已发送 \(timeout)s"
                            self.setTitle("已发送 \(timeout)s", for: UIControlState.normal)
                            self.isUserInteractionEnabled = false
                            self.isEnabled = false
                        }
                    })
                    timeout -= 1
                }
            })
            //启动时间源
            self.timer?.resume()
        }
    }
}



三丶注意

 1.不需要调用DispatchSource.cancel()              
 2.DispatchSourceTimer必须是全局变量
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 因为要结局swift3.0中引用snapKit的问题,看到一篇介绍Xcode8,swift3变化的文章,觉得很详细...
    uniapp阅读 4,500评论 0 12
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,242评论 25 708
  • 中心医院东区
    申美珍阅读 150评论 0 0
  • 到今年7月26日就是八周年了。 可是在这之前就分手了。 熬过了七年之痒, 说好研究生一毕业就结婚。 最后都像是美梦...
    俞末末爱吃鱼阅读 348评论 0 0
  • 初春时节,来到此处。山间的一个角落,远处有山,山上有树,树上有云。 这里有常住人几许,有花白土狗一只,有常往来人员...
    唐二同学阅读 750评论 3 1