Markdown

Markdown

Displaying styled text in an iOS app has always been a hassle, resorting either to an HTML view or cramming together attributed text, but now there's a more convenient option, markdown support provided by iOS 15. And now I have a reason to upgrade my Talk Dim Sum app requirement to iOS 15 (more persuasive to users than "because, bugs").

The flutter way to do this is like the flutter way to do everything, use a markdown widget:

Widget build(BuildContext context) => Markdown(data: dish.description);

The iOS way to do this, as with localization, is to overload the Text view:

Text("**this is bold**)

If you don't want the text parsed as markdown, then, as with localization, you need to specify that:

Text(verbatim: "**this is not bold**")

Unless the argument is not a string literal. In which case, it won't get parsed as markdown, so you need to pass in an AttributedString that parses the markdown. So I added a markdown property to my dish struct:

 var markdown: AttributedString {
        (try? AttributedString(markdown: description) ?? AttributedString()
    }

But wait, there's more! If you have newlines in your markdown (and who doesn't?), they'll get removed unless you specify not to in the markdown parsing options:

 var markdown: AttributedString {
        (try? AttributedString(markdown: description, options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString()
    }

And now I can display markdown in my dish description view.

struct DescriptionView: View {
    var dish: Dish

    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            Text(dish.markdown)
        }
    }
}

But you can't go crazy with it. Right now, the only markdown supported is boldface, italics, strikethrough, inline code, and links. That last one is a surprise given the limited set, but I'll take it!

Subscribe to Technicat

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe