Swift 4.0 GCD 倒计时按钮

override func viewDidLoad() {
        super.viewDidLoad()
        //写一个按钮
        btn.frame.size = CGSize(width: 100, height: 50)
        btn.center = view.center
        btn.backgroundColor = .red
        view.addSubview(btn)
        btn.addTarget(self, action: #selector(timeChange), for: .touchUpInside)
        btn.setTitle("发送验证码", for: .normal)
    }

点击事件:

@objc func timeChange() {
        
        var time = 10
        let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: DispatchQueue.global())
        codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))  //此处方法与Swift 3.0 不同
        codeTimer.setEventHandler {
            
            time = time - 1
            
            DispatchQueue.main.async {
                self.btn.isEnabled = false
            }
            
            if time < 0 {
                codeTimer.cancel()
                DispatchQueue.main.async {
                    self.btn.isEnabled = true
                    self.btn.setTitle("重新发送", for: .normal)
                }
                return
            }
            
            DispatchQueue.main.async {
                self.btn.setTitle("\(time)", for: .normal)
            }
            
        }
        
        codeTimer.activate()
        
    }

效果图:

Swift 4.0 GCD 倒计时按钮_第1张图片


注意:点击事件中的 self.btn.isEnabled  self.btn.setTitle 须放在主线程中进行,不然控制台报错,截图如下:

Swift 4.0 GCD 倒计时按钮_第2张图片

你可能感兴趣的:(移动开发,碎片代码记录)