@objc func textFieldChanged(_ textField: UITextField) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
self.shouldEnableBtn()
})
}
在这里,如果我再次输入textFieldChanged,我想取消现有的调度并开始新的调度。
答案 0 :(得分:1)
您可以使用DispatchWorkItem
类,该类允许您分别取消任务。
let workItem = DispatchWorkItem {
self.shouldEnableBtn()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: workItem)
// To cancel the work-item task
workItem.cancel()
最好将OperationQueue
用于以下任务:
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
// Add operation in the queue
operationQueue.addOperation {
self.shouldEnableBtn()
}
// Cancel to on-going operation by
operationQueue.cancelAllOperations()
// Pause to on-going operation by
operationQueue.isSuspended = true