如何在 Swift 的 NSTextView 中找到文本插入点位置?

How to find the text insertion point position in an NSTextView in Swift?

在 NSTextView 中,我想找到插入符号或选择的开始作为整数放置的位置。我该怎么做?

我试过这个语句:

@IBOutlet var mainTextField: NSTextView!

let theSelectedRange = mainTextField.selectedRange
cursorPosition = mainTextField.offset(from: mainTextField.beginningOfDocument, to: theSelectedRange.start)

但我收到错误消息:

Value of type 'NSTextView' has no member 'offset'

我看到了this question,但由于经验不足,我无法翻译Swift中的解决方案。

let selectedRange = self.textViewIn.selectedRanges.last
print(selectedRange ?? "No Selected")

输出:NSRange: {0, 3})

let insertionPointIndex = myTextView.selectedRanges.first?.rangeValue.location