How to separate attributes from a NSAttributed String and apply these attributes on other string?

↘锁芯ラ 提交于 2019-12-11 01:02:49

问题


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.



来源:https://stackoverflow.com/questions/37456522/how-to-separate-attributes-from-a-nsattributed-string-and-apply-these-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!