2017-08-28 128 views
0

我有一個NSTextField關鍵通知。當按鍵被按下時,我想檢查插入位置是否位於位置0:執行某項操作,否則執行默認操作。NSTextField購物車的位置

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?

但我不能讓他們對雨燕

工作

回答

1

圖出來:

self.currentEditor()?.selectedRange.location