0

Is there any way of getting the current cursor position in a NSTextField? I only find answers to UITextField which doesn't work for osx:

if let selectedRange = textField.selectedTextRange{
  let cursorPosition = textField.offset(from: textField.beginningOfDocument,to: selectedRange.start)
}

Many Thanks!

JFS
  • 2,992
  • 3
  • 37
  • 48
  • Here's how to set the selected range: [Highlight a selection in NSTextField](https://stackoverflow.com/questions/32376649/highlight-a-selection-in-nstextfield). – Willeke Dec 17 '18 at 07:14
  • @Willeke, thanks! Why do you never issue an answer? – JFS Dec 17 '18 at 18:27
  • Because short answers are downvoted and in this case a link to an answer isn't an answer. – Willeke Dec 18 '18 at 06:23

2 Answers2

2
  • Solution 1 (Obtained through NSViewController):

    let location = (viewController.view.window?.firstResponder as? NSText)?.selectedRange.location
    
  • Solution 2 (Obtained through NSTextField):

    let location = textField.currentEditor()?.selectedRange.location
    
jqgsninimo
  • 6,562
  • 1
  • 36
  • 30
1

I'm using this snippet to find a cursor location for NSTextField:

let currentEditor = textField.currentEditor() as? NSTextView
let caretLocation = currentEditor?.selectedRanges.first?.rangeValue.location // Int
Max Potapov
  • 1,267
  • 11
  • 17