How to separate attributes from a NSAttributed Str

2019-07-21 08:18发布

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.

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-21 08:53

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.

查看更多
\"骚年 ilove
3楼-- · 2019-07-21 09:05

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.

查看更多
登录 后发表回答