2017-09-25 52 views
0

清除事件我有一個視圖控制器與鏈接到一個IBAction爲一個NSButton假設perform()。該按鈕與返回鍵相同。 不過返回鍵也被用在了其他臨時措施。在沒有涉及到以前的視圖控制器的其他文件,我有一個的NSTextField這是可編輯的,所以返回鍵將驗證文本更改。如何在斯威夫特

我想驗證我的文字兵不血刃perform()從功能等效鍵按鈕調用。

目前我發現的唯一解決方案是發送通知textIsBeingEditing當我的文本字段成爲FirstResponder和其他代理函數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(),但我完全不知道如何使用它

+0

繼續[在Swift中取消鍵盤事件](https://stackoverflow.com/questions/46401695/cancel-key-event-in-swift?noredirect=1#comment79769275_46401695) – Willeke

回答

0

不要使用通知,請使用委託方法optional func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool來驗證文本字段的值。

+0

是的,我這樣做。但按鈕事件'進行()'仍然是所謂不幸... – DEADBEEF

+0

這是默認和默認按鈕的預期行爲。當按鈕應該抓住鑰匙時,哪個控件被聚焦? – Willeke

+0

集中控制應該是'NSTextfiled',但我看到當我在'NSTextField'上拼寫時,函數'becomeFirstResponder'被調用並且緊隨其後(即沒有做任何事情),函數'resignFirstRespoinder'也被調用。這是正常的嗎? – DEADBEEF