编辑NSTextField时检测箭头/输入键

时间:2017-11-30 18:15:46

标签: cocoa nstextfield

我无法找到解决此问题的最新信息。 如何在编辑NSTextField

时监控箭头键按下之类的内容

从我抬起头来看: - 未调用NSControlTextEditingDelegate函数(我不知道如何使用它们) - NSTextFieldDelegate函数不会列出可在此处运行的内容

2 个答案:

答案 0 :(得分:2)

设置文本字段的委托:

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
}

此链接Recognize if user has pressed arrow key while editing NSTextField swift

中有更多深入解释

答案 1 :(得分:0)

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)
    }
}