Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 15 beta 4: AttributedString with Markdown not rendering in Text in SwiftUI?

Tags:

swiftui

ios15

I assumed this was a iOS 15 beta 1 or 2 bug, but as of beta 4 I'm still seeing this behavior, so perhaps I'm doing something wrong: Text is supposed to render AttributedStrings with Markdown. It appears to render correctly when a direct String literal is passed into the Text, but not when the AttributedString is a variable. Am I doing something super dumb?

struct ContentView: View {
    var text = AttributedString("**Hello**, `world`! Visit our [website](https://www.capitalone.com).")

    var body: some View {
        VStack {
            Text("**Hello**, `world`! Visit our [website](https://www.capitalone.com).")
                .padding()

            Text(text)
                .padding()
        }
    }
}

enter image description here

like image 921
UberJason Avatar asked Sep 11 '25 17:09

UberJason


1 Answers

If you pass Markdown directly into a Text.init(), SwiftUI will auto-convert it into an AttributedString.

However, to go from a Markdown string to an AttributedString, you need to use an explicit AttributedString(markdown:options:baseURL:) initialiser. For example:

var text = try! AttributedString(markdown: "**Hello**, `world`! Visit our [website](https://www.capitalone.com).”)

Note that this initialiser throws if the conversion can’t be made correctly. I’ve used try! here because your example Markdown will definitely convert, but depending on the source of the Markdown text you may want to handle a thrown error a little more intelligently.

like image 73
Scott Matthewman Avatar answered Sep 14 '25 09:09

Scott Matthewman