Search code examples
iosmacosnsattributedstringfoundationnsattributedstringkey

How do I change the appearance of Markdown-styled text in an AttributedString?


WWDC 2021 introduced new AttributedString APIs in Foundation, including Markdown support. I'd like to change the appearance of .stronglyEmphasized text in an AttributedString created via markdown, to make the emphasised text's foreground colour red (as well as being bold), for example. From what I can work out it's something like:

let attributedString = try! AttributedString(markdown: "This string *has* some markdown")
let transformed = attributedString.transformingAttributes(\.stronglyEmphasized) { attribute in
    attribute.replace(with: .foregroundColor, value: Color.red)
}

But this tells me that "Reference to member 'stronglyEmphasized' cannot be resolved without a contextual type" and "Generic parameter 'U' could not be inferred." which is singularly unhelpful.


Solution

  • Turns out what you actually need to do in this situation is keep the existing .stronglyEmphasised attribute and also add the .foregroundColor attribute (this way those markdown-related attributes are still there so Text() gets to turn them into bold, etc), so more like this:

    let stronglyEmphasized = AttributeContainer()
        .inlinePresentationIntent(.stronglyEmphasized)
    
    let stronglyEmphasizedRed: AttributeContainer = AttributeContainer()
        .inlinePresentationIntent(.stronglyEmphasized)
        .foregroundColor(.red)
    
    var attributedString = try! AttributedString(markdown: markdown)
    attributedString.replaceAttributes(stronglyEmphasized, with: stronglyEmphasizedRed)