How to render raw markdown content in SwiftUI

In this article, we will learn how to render raw markdown content in Text view in SwiftUI.

Sometimes, we want the Text view to display the text as we have specified. Suppose I have specified **CodeSpeedy** within the Text view, it will be automatically formatted and displayed in bold.

Here we can prevent that by storing the text in a variable or by using the Text(verbatim:) initializer.

Using the Text(verbatim:) initializer

We can render raw, unformatted markdown symbols in the Text view by using the Text(verbatim:) initializer. This will prevent both markdown and localization entirely.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack (spacing: 30) {
            Text("This is a **Markdown** example")
                .font(.title2)

            Text(verbatim:"This is a **raw Markdown** example")
                .font(.title2)
        }
    }
}

Here, the first Text view will display a string with markdown formatting, and the second Text view will display a string with raw markdown characters.

Output:

Render raw markdown content in SwiftUI

Storing the text in a variable

We can also display the raw markdown symbol without any formation by storing the text in a variable.

First of all, I will declare a variable with the value of markdown characters and pass the variable within the Text view to display raw markdown text.

Example

import SwiftUI

struct ContentView: View {
    
    let rawMarkdown = "This is a **raw Markdown** example"
    
    var body: some View {
        Text(rawMarkdown)
            .font(.title2)
    }
}

In the above code, I have declared a variable called rawMarkdown, which holds a simple markdown text.

Then, I have used a Text view to display the value of rawMarkdown variable and the font size is set to title2.

Output:

Render raw markdown content in SwiftUI

Leave a Reply

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