Reputation: 3152
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
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
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