如何在Swift中清除事件 [英] How to clear event in Swift

查看:94
本文介绍了如何在Swift中清除事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ViewController,它的NSButton链接到IBAction,例如 perform()。该按钮等效于返回键。
但是,返回键也用于其他临时操作。在另一个与以前的ViewController不相关的文件中,我有一个可编辑的NSTextfield,因此返回键将验证文本更改。

I've a ViewController with a NSButton linked to a IBAction let's say perform(). The button is key equivalent to the return key. However the return key is also used in for a other temporary action. In an other file no related to previous ViewController, I have a NSTextfield which is editable, so the return key would validate the text changes.

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

I would like to validate my text without firing perform() function called from the key equivalent button.

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

For the moment the only solution I found is to send a notification textIsBeingEditing when my text field becomeFirstResponder and an other when the delegate function controlTextDidEndEditing.

这是我的通知的选择器:

Here is the selector of my notification:

@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…
    }
}

没有任何办法取消按键事件,以防止在我设置 myButton.action = #selector(self.perform(_ :)后立即触发 perform() ))
我看到了一个名为 flushBufferedKeyEvents()的函数,但我完全不知道如何使用它

Isn't any way to cancel the key event in order to prevent perform() to be fired just after I set myButton.action = #selector(self.perform(_:)) ? I see a function called flushBufferedKeyEvents() but I totally doesn't know how to use it

推荐答案

不要使用通知,请使用委托方法可选的func控件(_控件:NSControl,textShouldEndEditing fieldEditor:NSText)->布尔验证文本字段的值。

Don't use notifications, use the delegate method optional func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool to validate the value of the text field.

这篇关于如何在Swift中清除事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆