【问题标题】:How to separate attributes from a NSAttributed String and apply these attributes on other string?如何从 NSAttributed 字符串中分离属性并将这些属性应用于其他字符串?
【发布时间】:2016-05-26 09:16:08
【问题描述】:

例如。就像我们有一个 NSAttributed 字符串,我们需要将字符串和属性分开,然后在其他相同长度的字符串上使用这些属性。

【问题讨论】:

  • 您能否提供一个示例,说明您的预期输入和预期输出?

标签: ios swift nsattributedstring swift2.2


【解决方案1】:

一个 NSAttributedString 对于字符串的不同范围可能有不同的属性。

要提取这些属性,可以使用enumerateAttributesInRange 方法。

我们准备一个元组数组来保存结果:

var extractedAttributes = [(attributes: [String:AnyObject], range: NSRange)]()

每个元组将保存 NSAttributedString 中特定范围的属性。

现在我们迭代 NSAttributedString 并用结果填充数组:

attributedString.enumerateAttributesInRange(NSRange(location: 0, length: attributedString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, stopEnumerating) in
    extractedAttributes.append((attributes: dict, range: range))
}

填充数组后,您可以访问内容:

for item in extractedAttributes {
    print(item.attributes)
    print(item.range)
}

然后,您就拥有了创建具有这些属性的新属性字符串所需的一切:您拥有 NSAttributedString 中每个属性的范围和相应的属性。

【讨论】:

    【解决方案2】:

    你应该从 NSAttributedString 看看这个方法

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

    通过在 NSAttributedString 处调用此方法,您将收到范围内应用的所有属性。只需将所有字符串指定为范围。然后用这些属性创建新的属性字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2014-10-13
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      相关资源
      最近更新 更多