Swift 3 获取textview子字符串的属性

Swift 3 get attributes of textview sub string

我有一个包含多个段落的文本视图。每个字符串都可以采用不同的格式,例如,一些字符串是粗体,而另一些则使用斜体。

如何获取特定子字符串的属性并获取该子字符串之前的属性?

例如,我想获取所选文本的属性以及显示在它之前的文本。

这是我目前所拥有的。

let range: UITextRange = textView.selectedTextRange!
let selectedText = textTV.text(in: range)
let previousRange: UITextRange = textView.textRange(from: textView.beginningOfDocument, to: range.start)!
let previousText = textTV.text(in: previousRange)

有了这个我就可以得到用户选择的字符串。以及它背后的文字。

但是我不知道如何撕掉那个字符串的属性。

您可以枚举属性并将其应用于新文本:

textView.attributedText.enumerateAttributes(in: textView.selectedRange, options: .longestEffectiveRangeNotRequired) { (attributes, range, stop) in
    // do what you need
}

描述:

Executes the block for each attribute in the range. If this method is sent to an instance of NSMutableAttributedString, mutation (deletion, addition, or change) is allowed, as long as it is within the range provided to the block; after a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator basically assumes any change in length occurs in the specified range.) For example, if block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range.

如果您只是在寻找给定范围的属性文本,并且您有 NSLayoutManager 的子类,您可以调用 textStorage.attributedSubstring(from: glyphRange)。这里的glyphRange来自NSLayoutManager的子类调用的enumerateLineFragments方法。

只是把它放在那里以防万一有人需要它!