Swift: 延迟通知直到其他通知完成

Swift: delay notification until other notification finish

我创建classCurrencyTextField子classUITextField
它有通知:
NotificationCenter.default.addObserver(self, selector: #selector(self.textDidChange(_:)), name: NSNotification.Name.UITextFieldTextDidChange, object: self)

ViewController 我有 var currencyTextField: CurrencyTextField!
它也有 currencyTextField.addTarget(self, action: #selector(priceTextFieldDidChange(_:)), for: .editingChanged)

但是 CurrencyTextField 中的通知比 ViewController 慢。有没有办法先在 CurrencyTextField 调用中发出通知?

我唯一的解决方案是在 ViewController

上添加 DispatchQueue.main.asyncAfter

您可以创建新的委托人

protocol TextChangeDelegate: class {
    func textFieldDidChange(_ textField: TextField)
}

在 TextField 中 class 在 textDidChange 方法中添加以下行

@objc
private func textDidChange(_ textField: UITextField) {
    textChangeDelegate?.textFieldDidChange(self)
}

然后使 UIViewController 符合 TextChangeDelegate 并实现

func textFieldDidChange(_ textField: TextField)

而不是使用

currencyTextField.addTarget(self, action: #selector(priceTextFieldDidChange(_:)), for: .editingChanged)