1
    @objc func textFieldChanged(_ textField: UITextField) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
            self.shouldEnableBtn()
        })
}

在这里,如果我再次输入 textFieldChanged,我想取消现有的调度并重新开始。

4

1 回答 1

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
于 2018-10-04T06:38:45.300 回答