问题描述
例如就像我们有一个NSAttributed字符串,我们需要将字符串和属性分开,然后在相同长度的其他字符串上使用这些属性.
eg. Like we have a NSAttributed string and we need to separate string and attributes, then use these attributes on other string of same length.
推荐答案
对于字符串的不同范围,NSAttributedString可能具有不同的属性.
An NSAttributedString may have different attributes for different ranges of the string.
要提取这些属性,可以使用enumerateAttributesInRange
方法.
To extract these attributes, you can use the enumerateAttributesInRange
method.
我们准备了一个元组数组来保存结果:
We prepare an array of tuples to hold the results:
var extractedAttributes = [(attributes: [String:AnyObject], range: NSRange)]()
每个元组将在NSAttributedString中保存特定范围的属性.
Each tuple will hold the attributes for a specific range in the NSAttributedString.
现在,我们遍历NSAttributedString并使用结果填充数组:
Now we iterate on the NSAttributedString and populate the array with the results:
attributedString.enumerateAttributesInRange(NSRange(location: 0, length: attributedString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, stopEnumerating) in
extractedAttributes.append((attributes: dict, range: range))
}
一旦数组被填充,您就可以访问其中的内容:
Once the array is populated, you can access the contents:
for item in extractedAttributes {
print(item.attributes)
print(item.range)
}
然后您将需要创建具有以下属性的新属性字符串:NSAttributedString中具有每个属性的范围和相应的属性.
And from there you have all you need to create new attributed strings with these attributes: you have the range and the corresponding attributes for each one in the NSAttributedString.
这篇关于如何从NSAttributed字符串中分离属性并将这些属性应用于其他字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!