JFS
JFS

Reputation: 3152

NSTextField Cursor Position

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!

Upvotes: 0

Views: 1881

Answers (2)

jqgsninimo
jqgsninimo

Reputation: 7068

  • 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
    

Upvotes: 3

Max Potapov
Max Potapov

Reputation: 1337

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

Upvotes: 1

Related Questions