//前提是新建一个按钮 @IBOutlet weak var edit: UIButton!
func timeChange() {
var time = 100 //从100倒计时
let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: DispatchQueue.global())
codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))
codeTimer.setEventHandler {
time = time - 1
DispatchQueue.main.async {
self.edit.isEnabled = false//点击按钮后,禁用按钮显示倒计时
}
if time < 0 {
codeTimer.cancel()
DispatchQueue.main.async {
self.edit.isEnabled = true
self.edit.setTitle("测试", for: .normal)
}
return
}
DispatchQueue.main.async {
self.edit.setTitle("\(time)", for: .normal)
}
}
codeTimer.activate()
}
//调用时直接在同样的按钮里带入函数就可以
@IBAction func edit(_ sender: Any) {
timeChange()
}