Rendering mark down content in text

By | September 16, 2024

Quite often, while dealing with text contents, we come across questions like ‘how to render mark down content in text?’ SwiftUI has built-in support for rendering Markdown, including bold, italic, links, and more. It’s literally built right into SwiftUI’s Text view, so you can write code like this:

   VStack {
            Text("This is shows as regular text.")
            Text("* This part is **bold** text, this is *italic* text, and this is ***bold, italic*** text.")
            Text("~~A strikethrough example~~")
            Text("`Monospaced works too`")
            Text("Visit Google: [click here](https://google.com)")
        }

The link is tappable and it will be ind default tint color of your app. It can be modified with .tint() modifier.

Text("Visit Google: [click here](https://google.com)")
                .tint(.green)

This automatic Markdown conversion happens because SwiftUI interprets those strings as being instances of LocalizedStringKey – strings that can be localized by our app. This means if you want to create Markdown text from a property or variable, you should mark it explicitly as being LocalizedStringKey to get the Markdown rendering:

struct ContentView: View {
    let markdownText: LocalizedStringKey = "* This is **bold** text, this is *italic* text, and this is ***bold, italic*** text."

    var body: some View {
        Text(markdownText)
    }
}

If you wanted the original text unchanged – i.e., you wanted the raw, unformatted Markdown symbols to be left in place – just remove the LocalizedStringKey annotation. Alternatively, you can disable both Markdown and localization entirely using the Text(verbatim:) initializer.

Leave a Reply

Your email address will not be published. Required fields are marked *