skip to Main Content

My SwiftUI app is decoding some JSON into an object (Landmark) and then converting the text into an AttributedString in order to display bold and italic text. This works fine. But then the AttributedString output ignores the line breaks (n) that were working before being converted into AttributedStrings. Is there a way I can keep both the bold-italic text AND the line breaks?
Here is my code (the relevant parts)

struct DetailTabView: View {
var text: String

var body: some View {
    let markdownText: AttributedString = try! AttributedString(markdown: text)

Text(markdownText)

To give an example of the JSON:

"The word *danjō* simply means platform. *Garan*, which derives from the Sanskrit *saṁghārāma*, refers to the dwelling of a Buddhist monastic community (or *sangha*).nThe word has been used in Japan to denote to the area of a temple complex where the most essential structures are located."

When I use the AttributedString, the words danjō and Garan appear in italics as expected. But the line break (at n) is lost. The result is reversed if I just use "text" without the conversion to AttributedString.
Can anyone point me in the right direction?

2

Answers


  1. The init(markdown: method provides options, try inlineOnlyPreservingWhitespace

    let markdownText = try! AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)))
    
    Login or Signup to reply.
  2. You can try adding the

    MarkdownParsingOption

    inlineOnlyPreservingWhitespace

    as below

    let markdownText: AttributedString = try! AttributedString(markdown: text, 
    options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace))
    

    Please feel free to improve the answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search