Is there a way to convert a plain text string containing Markdown text (i.e., # heading
, * list item
, [a link](http://example.com)
, etc.) to an NSAttributedString
in Swift? I suppose I could perform some kind of regex search for the indices of certain MD patterns and create the attributed string from that, but that seems clunky and feels wrong to me.
Is there an easier method?
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.
You can try using a third party library like Down. It's a lot simpler than creating your own parsing engine.
After installing this library, you can use the following code to parse markdown strings to NSAttributedString
s:
let downMdStr = Down(markdownString: yourMarkdownString)
let attributedStr = try? down.toAttributedString()
attributedStr
is an NSAttributedString
. However, it may be nil
if any error occurs, so remember to perform checking.
iOS 15 now supports Markdown parsing directly by NSAttributedString
/AttributedString
class.
let markdownString = "..."
let attrString = try AttributedString(markdown: markdownString)
See details here: https://developer.apple.com/documentation/foundation/attributedstring
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With