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

时间:2017-03-08 07:31:15

标签: swift xcode cocoa macos-sierra nstextview

如何从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)

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

3 个答案:

答案 0 :(得分:3)

怎么样?
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:)

答案 1 :(得分:0)

这可能对您有所帮助:

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)
}

答案 2 :(得分:0)

Swift 5中的代码段。这不是很难,但是可以重复

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)