常用方法

2021-10-20  本文已影响0人  _风雨

Button倒计时

func showCountdownTime(_ time: Int, button: UIButton?) {
    var time = time
    
    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 {
            button?.isEnabled = false
        }
        
        if time < 0 {
            codeTimer.cancel()
            
            DispatchQueue.main.async {
                button?.isEnabled = true
                button?.setTitle("发送验证码", for: .normal)
            }
            return
        }
        
        DispatchQueue.main.async {
            button?.setTitle("\(time)秒", for: .normal)
        }
    }
    codeTimer.activate()
}
上一篇 下一篇

猜你喜欢

热点阅读