1

I was wondering if it is possible to import markdown files into your SwiftUI project (in Xcode) and then display the contents of the file inside of an SwiftUI view? It would be pretty neat if one have a lot of text to process and just import it by a simple method?

I've tried using:

import SwiftUI

struct ShowMarkdown: View {
    // Get the path to your markdown file.
    let filepath = Bundle.main.url(forResource: "filename", withExtension: "md")
    
    var body: some View {
        // Show the markdown.
        Text(try! AttributedString(contentsOf: filepath!))
    }
}

The problem with using above code is that for one thing it doesn't display the headers correctly. I want it to look like what you see in a preview of an simple Markdown file.

1 Answers1

1

Text views can display Markdown directly, but rather than initialise with a String variable, you'll need to use LocalizedStringKey

struct ShowMarkdown: View {
    // Get the path to your markdown file.
    
    var text: LocalizedStringKey {
        let filepath = Bundle.main.url(forResource: "filename", withExtension: "md")!
         return LocalizedStringKey(try! String(contentsOf: filepath))
    }


    var body: some View {
        // Show the markdown.
        Text(text)
    }
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160