如何清除Swift中的事件

时间:2017-09-25 15:02:21

标签: objective-c swift cocoa

我有一个带有NSButton链接到IBAction的ViewController让我们说perform()。该按钮等同于返回键。 但是,返回键也用于其他临时操作。在与之前的ViewController无关的其他文件中,我有一个可编辑的NSTextfield,因此返回键将验证文本更改。

我想验证我的文本而不会触发从等效键等按钮调用的perform()函数。

目前,我找到的唯一解决方案是在我的文本字段成为FirstResponder时发送通知textIsBeingEditing,在委托函数controlTextDidEndEditing时发送另一个通知。

以下是我的通知选择器:

@objc func trackNameIsBeingEditedNotification(_ notification: Notification) {
    guard let value = notification.userInfo?["trackNameIsBeingEdited"]
      as? Bool else {
        return
    }

    if value {
      backButton.keyEquivalent = ""
      backButton.action = nil
    } else {
      myButton.keyEquivalent = "\r"
      myButton.action = #selector(self.perform(_:))
      // Here the `perform()` function is fired but I would avoid this behaviour…
    }
}

在我设置perform()之后,是否有办法取消关键事件以阻止myButton.action = #selector(self.perform(_:))被解雇? 我看到一个名为flushBufferedKeyEvents()的函数,但我完全不知道如何使用它

1 个答案:

答案 0 :(得分:0)

请勿使用通知,请使用委托方法optional func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool来验证文本字段的值。