Markdown in SwiftUI Text Views
Starting with iOS 15 and macOS 12, SwiftUI Text views have built-in support for parsing Markdown when created with a `LocalizedStringKey`. This feature simplifies working with Markdown-formatted text in your SwiftUI applications. However, there are some considerations to keep in mind regarding how Markdown is parsed and when it is applied. In this guide, we’ll explore how to use Markdown in SwiftUI Text views effectively.
Parsing Markdown with LocalizedStringKey:
When you create a Text view using a string literal, SwiftUI will automatically parse the Markdown content if you use the `LocalizedStringKey` initializer:
// Markdown will be parsed by Text view.
Text("Markdown string with *emphasized* text.")
In this example, the Markdown content within the string is parsed and displayed with the appropriate formatting.
No Markdown Parsing with String Variable:
If you create a Text view using a string variable, Markdown will not be parsed by default:
struct ContentView: View {
let str = "Markdown string with *emphasized* text."
var body: some View {
// Markdown won't be parsed by Text view.
Text(str)
}
}
In this case, the text is displayed as-is, without Markdown formatting.
No Markdown Parsing with `init(verbatim:)`:
Markdown will also not be parsed when you create a Text view using `init(verbatim:)`:
// Markdown won't be parsed by Text view.
Text(verbatim: "Markdown string with *emphasized* text.")
In this scenario, the content is treated as plain text.
Parsing Markdown without Localization:
If you want to parse Markdown but do not need to localize the text, you can create an `AttributedString` from the Markdown content and then pass it to a Text view:
struct ContentView: View {
// Force unwrap because we have a valid Markdown string.
let attributedString = try! AttributedString(
markdown: "Markdown string with *emphasized* text.")
var body: some View {
Text(attributedString)
}
}
Note that Markdown is parsed slightly differently by `AttributedString` and by Text. When localized, Text implicitly uses the `inlineOnlyPreservingWhitespace` parsing option.
Conclusion:
iOS 15 and macOS 12 bring native Markdown support to SwiftUI Text views when created with a `LocalizedStringKey`. Understanding how Markdown is parsed based on how you create the Text view is crucial for formatting and displaying text effectively in your SwiftUI applications. Whether you need to parse Markdown, localize text, or simply display plain text, SwiftUI provides the flexibility to meet your requirements.