0

WWDC 2021在 Foundation 中引入了新的 AttributedString API ,包括对 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)
}

但这告诉我“没有上下文类型就无法解决对成员 'stronglyEmphasized' 的引用”和“无法推断通用参数 'U'”。这非常无益。

4

1 回答 1

1

事实证明,在这种情况下您实际需要做的是保留现有.stronglyEmphasised属性并添加.foregroundColor属性(这样那些与降价相关的属性仍然存在,因此可以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)
于 2021-11-16T10:11:38.050 回答