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必须是全局变量

你可能感兴趣的:(Swift_技巧(4)_GCD倒计时实现(swift3.0))