How to render dynamic Markdown strings in SwiftUI?

October 12, 20242 min read#swift, #ios, #swiftui

SwiftUI has supported rendering Markdown texts natively recently, and it’s a great convenience to quickly render formatted texts using Text View

struct TestView: View {
    var body: some View {
        VStack {
            Text("- This is **bold text**\n- This is *italic text*.")
                .font(.title)
        }
    }
}

#Preview {
    TestView()
}

correct

But to my surprise, when I’m trying to move the title to a variable, the following code doesn’t render the Markdown strings at all

struct TestView: View {
    let title: String
    var body: some View {
        VStack {
            Text(title)
                .font(.title)
        }
    }
}

#Preview {
    TestView(title: "- This is **bold text**\n- This is *italic text*.")
}

wrong

Luckily, we can easily solve the issue by adding an extension to convert the string to an AttributedString before passing it to the Text view

struct TestView: View {
    let title: String
    var body: some View {
        VStack {
            Text(title.markdownToAttributed())
                .font(.title)
        }
    }
}

extension String {
    func markdownToAttributed() -> AttributedString {
        do {
            return try AttributedString(
                markdown: self,

                options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace)
            )
        } catch {
            return AttributedString(stringLiteral: self)
        }
    }
}

#Preview {
    TestView(title: "- This is **bold text**\n- This is *italic text*.")
}

correct

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024