Search code examples
swiftswiftui

How to add line breaks to markdown text in SwiftUI


I'm having trouble adding line breaks in markdown in Swift when I create the markdown text using an AttributedString. The first example works but the second is not working for me.

struct MarkdownText: View {
    var body: some View {
        VStack {
            Text("I am **bold**.\nI am *italic*.")
            Text(try! AttributedString(markdown: "I am **bold**.\nI am *italic*."))
        }
    }
}

Solution

  • You need to use the options property with .inlineOnlyPreservingWhitespace. Try this:

    Text(try! AttributedString(markdown: "I am **bold**.\nI am *italic*.", 
                               options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) //<- here