NSTextField获得购物车位置

时间:2017-08-28 11:46:19

标签: swift macos cocoa

我有一个带有密钥通知的NSTextField。当按下键时我想检查插入位置是否在位置0:做某事,否则做默认动作。

class ConsoleTextField: NSTextField {
    var commandHistory:[String] = []
    var commandPosition:Int = 0
    var keyDownMonitor:Any? = nil

    override func becomeFirstResponder() -> Bool {
        if keyDownMonitor == nil {
            keyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
                self.keyDown(with: $0)
                return $0
            }
        }
        return super.becomeFirstResponder()
    }

    override func textDidEndEditing(_ notification: Notification) {
        super.textDidEndEditing(notification)
        if let keyDownMonitor = keyDownMonitor {
            NSEvent.removeMonitor(keyDownMonitor)
        }

        keyDownMonitor = nil
    }

    override func keyDown(with event: NSEvent) {
            switch event.keyCode {
            case 125: // down arrow key
                // here I want to check current caret position in text field
            default:
                break
            }
        }
}

我看到相关问题,如下:

How to find caret position in an NSTextView?

但是我无法让它们在Swift上运行

1 个答案:

答案 0 :(得分:1)

弄清楚:

self.currentEditor()?.selectedRange.location