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.
问题:
回答1:
An NSAttributedString may have different attributes for different ranges of the string.
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)]()
Each tuple will hold the attributes for a specific range in the 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)
}
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.
回答2:
You should take a look at this method from NSAttributedString
attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject]
By calling this method at NSAttributedString you will receive all attributes applied in range. Just specify all string as range. And then create new attributes string with these attributes.