我有一个包含多个段落的 TextView 。每个字符串可以采用不同的格式,例如某些字符串是粗体,其他字符串使用斜体。
如何获取特定子字符串的属性以及该子字符串之前的子字符串的属性?
例如,我想获取所选文本及其之前显示的文本的属性。
这是我到目前为止所拥有的。
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.
关于Swift 3 获取textview子字符串的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44709478/