【问题标题】:How to get the selected string from a NSTextView in Swift?如何从 Swift 中的 NSTextView 中获取选定的字符串?
【发布时间】:2017-03-08 07:31:15
【问题描述】:

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

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

【问题讨论】:

标签: swift xcode cocoa macos-sierra nstextview


【解决方案1】:

怎么样

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

【讨论】:

  • 但是当 UITextView 中有表情符号时,这将不起作用。我在mainEditor.textStorage.string[range.lowerBound - 1]) 这一行遇到了错误。由Can't advance past endIndex 引起。 mainEditor.textStorage.string 打印 322,range.lowerBound - 1 打印 323。
  • 我看不到您评论中的代码如何引用答案。
【解决方案2】:

这可能对你有帮助:

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

【讨论】:

  • 谢谢 Mitesh,在我的工具箱中有这个代码 sn-ps 非常有用!
【解决方案3】:

Swift 5 中的代码 sn-p。这不是很难但重复

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)

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多