Use the CMTextAttributes class to define how different Markdown elements are styled. You can set three types of attributes:
- String attributes: Standard
NSAttributedString attributes. - Font attributes: For setting fonts and traits (supports automatic Dynamic-Type compliance on iOS).
- Paragraph attributes: For block-level styling like alignment or list markers.
Grouped attribute styling
Instead of setting attributes for every single node, use grouped methods to apply styles to specific element kinds (e.g., .anyHeader, .blockQuote, .inlineCode).
let textAttributes = CMTextAttributes()
// Set text color for all headers
textAttributes.addStringAttributes([ .foregroundColor: UIColor.blue], forElementWithKinds: .anyHeader)
// Set font and traits for headers
textAttributes.addFontAttributes([ .family: "Avenir Next" ], forElementWithKinds: .anyHeader)
// Set alignment for block quotes
textAttributes.addParagraphStyleAttributes([ .alignment: NSTextAlignment.center.rawValue], forElementWithKinds: .blockQuote)
let textAttributes = CMTextAttributes()
textAttributes.addStringAttributes([ .foregroundColor: UIColor(red: 0.0, green: 0.446, blue: 0.657, alpha: 1.0)],
forElementWithKinds: .anyHeader)
textAttributes.addFontAttributes([ .family: "Avenir Next" ,
.traits: [ UIFontDescriptor.TraitKey.symbolic: boldItalicTrait.rawValue]],
forElementWithKinds: .anyHeader)
textAttributes.addParagraphStyleAttributes([ .alignment: NSTextAlignment.center.rawValue],
forElementWithKinds: .blockQuote)