编辑 NSTextField 时检测 arrow/enter 键

Detecting arrow/enter keys when editing NSTextField

我找不到解决此问题的最新信息。 我如何在编辑 NSTextField 时监控方向键等操作?

据我查询: - NSControlTextEditingDelegate 函数没有被调用(我不知道如何使用它们) - NSTextFieldDelegate 函数未列出适用于此处的内容

keyDown doesn't seem to work with NSTextFields (it does for NSTextView),所以我在我这边所做的是子类化 NSTextFieldViewController 并添加这些方法:

import Cocoa

class MyTextField: NSTextField
{    
    override func keyUp(with event: NSEvent) {
        print("MyTextField keyUp key is %ld", event.keyCode)

        super.keyUp(with: event)            
    }
}

class MyTextView: NSTextView
{
    override func keyDown(with event: NSEvent) {

        print("MyTextView keyDown key is %ld", event.keyCode)

        super.keyDown(with: event)
    }    
}

class ViewController: NSViewController {

    override func keyUp(with event: NSEvent) {
        print("ViewController keyUp key is %ld", event.keyCode)

        super.keyUp(with: event)
    }
}

设置文本字段的委托:

textField.delegate = self

为协议添加以下继承:

class MyTextField : NSTextFieldDelegate, NSControlTextEditingDelegate { ...

并执行以下内容:

   func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if commandSelector == #selector(moveUp(_:)) {
        ...
    } else if commandSelector == #selector(moveDown(_:)) {
        ...
    } else if commandSelector == #selector(insertNewline(_:)) {
        ...
    }
    return true
}

这里有更深入的解释 link