swift通过NSAttributedString中的索引获取属性的范围



我有一个NSAttributedString,有两个属性

从0到5{0,5}->属性1

从6到10{6,10}->属性2

我使用

let attributes = textView.textStorage.attributes(at: 7, longestEffectiveRange: nil, in: NSRange(location: 0, length: textView.textStorage.length))

以获取索引7处的属性。

是否有可能在索引7中包含全部属性?

在我的例子中,我应该得到6-10

感谢

是的,可以使用NSAttributedString提供的enumerateAttributes。意味着获取字符串中每个属性的所有范围,并找到包含索引的范围

代码将像这个

var index = 7
attributeString.enumerateAttributes(in: NSRange(location: 0, length: attributeString.length), using: {
_, range, _ in
// if index in range
if range.contains(index) {
print("range: ", range)
// do your code here
}
})

最新更新