【发布时间】:2016-05-26 09:16:08
【问题描述】:
例如。就像我们有一个 NSAttributed 字符串,我们需要将字符串和属性分开,然后在其他相同长度的字符串上使用这些属性。
【问题讨论】:
-
您能否提供一个示例,说明您的预期输入和预期输出?
标签: ios swift nsattributedstring swift2.2
例如。就像我们有一个 NSAttributed 字符串,我们需要将字符串和属性分开,然后在其他相同长度的字符串上使用这些属性。
【问题讨论】:
标签: ios swift nsattributedstring swift2.2
一个 NSAttributedString 对于字符串的不同范围可能有不同的属性。
要提取这些属性,可以使用enumerateAttributesInRange 方法。
我们准备一个元组数组来保存结果:
var extractedAttributes = [(attributes: [String:AnyObject], range: NSRange)]()
每个元组将保存 NSAttributedString 中特定范围的属性。
现在我们迭代 NSAttributedString 并用结果填充数组:
attributedString.enumerateAttributesInRange(NSRange(location: 0, length: attributedString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, stopEnumerating) in
extractedAttributes.append((attributes: dict, range: range))
}
填充数组后,您可以访问内容:
for item in extractedAttributes {
print(item.attributes)
print(item.range)
}
然后,您就拥有了创建具有这些属性的新属性字符串所需的一切:您拥有 NSAttributedString 中每个属性的范围和相应的属性。
【讨论】:
你应该从 NSAttributedString 看看这个方法
attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject]
通过在 NSAttributedString 处调用此方法,您将收到范围内应用的所有属性。只需将所有字符串指定为范围。然后用这些属性创建新的属性字符串。
【讨论】: