有什么方法可以获得NSTextField
中的当前光标位置吗?我只找到UITextField
的答案,它不适用于osx:
if let selectedRange = textField.selectedTextRange{
let cursorPosition = textField.offset(from: textField.beginningOfDocument,to: selectedRange.start)
}
非常感谢!
-
解决方案1(通过NSViewController获得(:
let location = (viewController.view.window?.firstResponder as? NSText)?.selectedRange.location
-
解决方案2(通过NSTextField获得(:
let location = textField.currentEditor()?.selectedRange.location
我使用这个片段来查找NSTextField
:的光标位置
let currentEditor = textField.currentEditor() as? NSTextView
let caretLocation = currentEditor?.selectedRanges.first?.rangeValue.location // Int