识别整个窗口中的关键事件

时间:2016-08-15 18:11:07

标签: swift macos cocoa nstextview nsviewcontroller

我正在开发一个音译应用程序,它从NSTextView获取一些文本并将其音译并将其放入另一个NSTextView中, 我想要做的是,当用户键入一个单词并按下空格时键入句子我希望空格键触发一个动作,我指定将该句子分成单个单词的数组。 为了做到这一点,我试图覆盖viewController类中的keyDown函数:

override func keyDown(theEvent: NSEvent) {
    if (theEvent.keyCode == 49){
        print("pressed space")
    }
}

哪个不起作用,当我继承NSTextView类并覆盖其中的keyDown函数但我的textView停止输入文本时,它可以正常工作。 如何设置有效的空格键的关键事件?通过按空格键将句子分成单词数组的任何其他建议?

感谢

1 个答案:

答案 0 :(得分:0)

步骤1是将View Controller设置为NSTextField的委托。如果您使用笔尖或故事板,它将如下所示:

enter image description here

基本上用ctrl拖动来查看控制器并设置委托。

然后您可以对视图控制器中更改的文本做出反应:

import Cocoa

class ViewController: NSViewController {


override func controlTextDidChange(obj: NSNotification) {

    guard let textField = obj.object as? NSTextField else { return }

    if textField.stringValue.characters.last == " " {
        print(textField.stringValue.componentsSeparatedByString(" "))
    }

}
}

它将打印出以空格分隔的单词数组:

[“a”,“”]

[“a”,“boy”,“”]

[“a”,“boy”,“come”,“”]

[“a”,“boy”,“come”,“to”,“”]

[“a”,“boy”,“come”,“to”,“school”,“”]

您可能需要从数组中删除最后一项:

     override func controlTextDidChange(obj: NSNotification) {

    guard let textField = obj.object as? NSTextField else { return }

    if textField.stringValue.characters.last == " " {
        print(textField.stringValue.componentsSeparatedByString(" ").filter { $0 != "" })
    }

}

对于NSTextView,逻辑类似。从文本视图中按住Ctrl键将视图控制器设置为委托: enter image description here

然后使用以下代码:

  func textDidChange(obj: NSNotification) {

    guard let textView = obj.object as? NSTextView else { return }
    guard let stringValue = textView.textContainer?.textView?.string else { return }

    if stringValue.characters.last == " " {
        print(stringValue.componentsSeparatedByString(" ").filter { $0 != "" })
    }

}

它会正常工作:

enter image description here

相关问题