New lines not being rendered in SwiftUI's markdown

I'm trying the new markdown functionality in SwiftUI but it seems that trying to render markdown from an Attributed String inside a variable strips away any new lines.

This isn't the case when placing the raw markdown directly in the Text View's initialiser, as shown in the preview below.

Is this a bug or is there a way to retain new lines when using Attributed String? None of the options seem to help.

Thanks!

import SwiftUI

struct markdown_test: View {

    let attStr = try! AttributedString(markdown: """

Hello **World** 👋🏻      \n\n\n\n

[This is a test](www.google.co.uk)
""")

    var body: some View {

        VStack(alignment: .leading) {
            Text(attStr)
            Text("Hello **World** 👋🏻\n[This is a test](www.google.co.uk)")
        }

    }

}

Answered by mralexhay in 682044022

This issue appears to have been fixed on Monterey Beta 3.

You have to add the .inlineOnlyPreservingWhitespace option when initialising the AttributedString.

struct MarkdownTest: View {

    let attrStr = try! AttributedString(markdown: "Hello **World**!\n[This is a link](www.google.com)", options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace))

    var body: some View {
        Text(attrStr)
            .padding()
    }
} 

The CommonMark specification says that multiple newlines are equivalent to a single paragraph break, which is what you're seeing here:

Multiple blank lines between paragraph (sic) have no effect.

— 4.8 Paragraph, from v. 0.29

Accepted Answer

This issue appears to have been fixed on Monterey Beta 3.

You have to add the .inlineOnlyPreservingWhitespace option when initialising the AttributedString.

struct MarkdownTest: View {

    let attrStr = try! AttributedString(markdown: "Hello **World**!\n[This is a link](www.google.com)", options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace))

    var body: some View {
        Text(attrStr)
            .padding()
    }
} 
15

Add two spaces at the end of the line and then add an escape character ' \n'.

AttributedString( markdown: "**Thank you!** Please visit our [website](https://example.com)  \nThis is second line")

Output:

New lines not being rendered in SwiftUI's markdown
 
 
Q