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

标签 swift attributes textview nsmutableattributedstring

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

相关文章:

ios - 如何跟踪 UICollectionView 索引

sql-server - 从 SQL Server 中的 xml 字段中选择日期列表

c# - 为什么属性目标 'typevar' 未记录?

asp.net-mvc - ReadOnly 属性在 ASP.NET MVC 模型中不起作用

android - 如何知道 TextView 是否在动画中?

android - 如何在 imageView 上设置文本?

ios - swift 中的 MVC 结构

swift - 尝试创建一个 Swift 扩展来替换字符串中的多次出现

ios - 如何使用 CollectionView/TableView Controller 实现滑动 View ?

Android - 带有以下文字的搜索栏