【问题标题】:How to copy all attributes from one AttributedString to another without converting to NSAttributedString?如何在不转换为 NSAttributedString 的情况下将所有属性从一个 AttributedString 复制到另一个?
【发布时间】:2023-02-08 02:07:29
【问题描述】:
我有一个 AttributedString,它有一组我直到运行时才知道的属性。现在我想附加/前置另一个字符串。如何使附加字符串具有与原始 AttributedString 相同的属性?从第一个字符复制属性没问题,因为整个 AttributedString 具有同类属性。
我看到我可以使用新的附加文本创建一个新的 AttributedString,然后在其上调用“setAttributes”,但是看不到从原始字符串中获取 AttributeContainer 的方法吗?有没有一种方法可以不涉及单独复制每个属性?
我看到这对于 NSAttributedString 是可行的,但是是否可以不转换为 NSAttributedString?
我希望我能做类似的事情:
let originalText: AttributedString // Some existing string with arbitrary attributes
var newText = AttributedString("text_I_want_to_prepend_to_originalText")
newText.setAttributes(originalText.getAttributes(at: 0))
newText.append(originalText)
【问题讨论】:
标签:
swift
nsattributedstring
attributedstring
【解决方案1】:
容器附加到每个AttributedString.Run(这是一系列具有相同属性的字符)。您可以通过以下方式访问它们:
newText.setAttributes(originalText.runs.first!.attributes)
显然,您应该仔细考虑如果字符串为空,这将如何工作,因为那样会崩溃。但基本方法是访问runs 属性。
runs 上有一个接受AttributeString.Index 的下标,因此与您的原始getAttributes(at: 0) 更精确匹配的版本将是:
newText.setAttributes(originalText.runs[originalText.startIndex].attributes)
【解决方案2】:
你可以使用init(_:attributes:) | Apple Developer Documentation
使用默认属性集:
let defaultAttributes = AttributeContainer().font(.body).foregroundColor(.green)
var newText = AttributedString("text_I_want_to_prepend_to_originalText",
attributes: string.runs.first?.attributes ?? defaultAttributes)