简体   繁体   English

如何从 NSAttributed 字符串中分离属性并将这些属性应用于其他字符串?

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

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.就像我们有一个 NSAttributed 字符串,我们需要将字符串和属性分开,然后在其他相同长度的字符串上使用这些属性。

An NSAttributedString may have different attributes for different ranges of the string.对于字符串的不同范围,NSAttributedString 可能具有不同的属性。

To extract these attributes, you can use the enumerateAttributesInRange method.要提取这些属性,您可以使用enumerateAttributesInRange方法。

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.每个元组将保存 NSAttributedString 中特定范围的属性。

Now we iterate on the NSAttributedString and populate the array with the results:现在我们迭代 NSAttributedString 并用结果填充数组:

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.从那里,您拥有了创建具有这些属性的新属性字符串所需的一切:您拥有 NSAttributedString 中每个属性的范围和相应的属性。

You should take a look at this method from NSAttributedString您应该从 NSAttributedString 中查看此方法

attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject]

By calling this method at NSAttributedString you will receive all attributes applied in range.通过在 NSAttributedString 调用此方法,您将收到范围内应用的所有属性。 Just specify all string as range.只需将所有字符串指定为范围。 And then create new attributes string with these attributes.然后使用这些属性创建新的属性字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM