Rob*_*ins 3 macos foundation nsattributedstring ios nsattributedstringkey
WWDC 2021在 Foundation 中引入了新的 AttributedString API,包括 Markdown 支持。例如,我想更改通过 markdown 创建.stronglyEmphasized的文本的外观AttributedString,使强调文本的前景色为红色(以及粗体)。据我所知,它是这样的:
let attributedString = try! AttributedString(markdown: "This string *has* some markdown")
let transformed = attributedString.transformingAttributes(\.stronglyEmphasized) { attribute in
attribute.replace(with: .foregroundColor, value: Color.red)
}
Run Code Online (Sandbox Code Playgroud)
但这告诉我“如果没有上下文类型,就无法解析对成员‘stronglyEmphasized’的引用”并且“无法推断通用参数‘U’”。这是毫无帮助的。
事实证明,在这种情况下您实际上需要做的是保留现有.stronglyEmphasised属性并添加该.foregroundColor属性(这样那些与 markdown 相关的属性仍然存在,因此Text()可以将它们变成粗体等),所以更像是这样:
let stronglyEmphasized = AttributeContainer()
.inlinePresentationIntent(.stronglyEmphasized)
let stronglyEmphasizedRed: AttributeContainer = AttributeContainer()
.inlinePresentationIntent(.stronglyEmphasized)
.foregroundColor(.red)
var attributedString = try! AttributedString(markdown: markdown)
attributedString.replaceAttributes(stronglyEmphasized, with: stronglyEmphasizedRed)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1215 次 |
| 最近记录: |