gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:19:09 26 4
gpt4 key购买 nike

我有一个包含多个段落的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com