In the session, I have seen a lot of examples of rainbow effects and I'd like to bring it into my app written by SwiftUI, but one thing missing is that I'm not sure how to implement customizable markdown analysis and how to set the style for it. Please help me, maybe give me some ideas? or just some suggestions.
Replies
What you need here is to create a new AttributeScope that contains the AttributeKey for your custom attribute, and pass that to the appropriate AttributedString(markdown:…) or AttributedString(localized:…) initializer. You can see that process in the What's New In Foundation session of WWDC '21.
Most AttributedString constructors that take Markdown text have an including: parameter that you can pass your scope type in.
-
Yep, I have seen that. But how to add a customize style for it, for instance, the rainbow effect in the session. Where should I add these styling code?
-
Do you mean that I should create a new
AttributeScopestructure to include all my customize styles? -
You should create an
AttributeScope-conforming type that contains your custom attributes and pass that scope as a parameter to theAttributedString(markdown:)orAttributedString(localized:)functions. This allows Foundation to parse your custom attribute from markdown, and apply it to the resulting attributed string. However, frameworks like AppKit/UIKit and SwiftUI will not understand how to render a custom attribute (such as a rainbow effect attribute) in their UI views. If you'd like your custom attribute to be transformed into attributes that are rendered by the UI frameworks, you can call the mutation functions such as thetransformingAttributes()function on the attributed string to, for example, change your custom rainbow attribute to a series of foreground color attributes before applying the attributed string to a view.