4

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

3

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I knew I was doing something dumb! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.