如何从 Swift 中的 NSTextView 中获取选定的字符串?

How to get the selected string from a NSTextView in Swift?

如何从 Swift 中的 NSTextView 中获取选定的字符串?

// create a range of selected text
let range = mainTextField.selectedRange()

// this works but I need a plain string not an attributed string
let str = mainTextField.textStorage?.attributedSubstring(from: range)

也许我必须添加一个中间步骤来获取完整的字符串,然后在其上应用范围?

怎么样

let str = mainTextField.text.substring(with: range)

编辑:

现在应该可以工作了:

let range = mainTextField.selectedRange()     // Returns NSRange :-/ (instead of Range)
let str = mainTextField.string as NSString?   // So we cast String? to NSString?
let substr = str?.substring(with: range)      // To be able to use the range in substring(with:)

这可能对您有帮助:

let textView = NSTextView(frame: NSMakeRect(0, 0, 100, 100))
let attributes = [NSForegroundColorAttributeName: NSColor.redColor(),
              NSBackgroundColorAttributeName: NSColor.blackColor()]
let attrStr = NSMutableAttributedString(string: "my string", attributes: attributes)
let area = NSMakeRange(0, attrStr.length)
if let font = NSFont(name: "Helvetica Neue Light", size: 16) {
  attrStr.addAttribute(NSFontAttributeName, value: font, range: area)
  textView.textStorage?.appendAttributedString(attrStr)
}

Swift5 中的代码片段。这不是很难但重复了

let string = textView.attributedString().string
let selectedRange = textView.selectedRange()
let startIndex = string.index(string.startIndex, offsetBy: selectedRange.lowerBound)
let endIndex = string.index(string.startIndex, offsetBy: selectedRange.upperBound)
let substring = textView.attributedString().string[startIndex..<endIndex]

let selectedString = String(substring)