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()
}
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*.")
}
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*.")
}