Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I pass a string containing markdown to custom view?

I want to pass a string containing markdown to a custom view and have the formatting done in that view.

Example:

struct MyTest: View {
    let text: String // Some other type needed here
    
    init(_ text: String) { self.text = text }
    
    var body: some View {
        Text(text)
        Text("*Inline*")
    }
}

Use the view, eg.: MyTest("*Test*")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This will produce the output:

*Test*
Inline

The goal is to get the output:

Test
Inline

Is it possible to have the formatting passed to the Text(text) line in the custom view?

>Solution :

The formatting markdown "magic" comes from this initialiser of Text, which takes a LocalizedStringKey. Since LocalizedStringKey conforms to ExpressibleByStringLiteral, Text("*Inline*") will call this initialiser, but Text(someStringVariable) will not.

So to format the markdown in the text property, you just need to call that initialiser. You can either make text a LocalizedStringKey itself:

struct MyTest: View {
    let text: LocalizedStringKey
    
    init(_ text: LocalizedStringKey) { self.text = text }
    
    var body: some View {
        Text(text)
        Text("*Inline*")
    }
}

Or create a LocalizedStringKey when creating the Text:

Text(LocalizedStringKey(text))

By using this initialiser of Text, you get the added benefit of localising the text! 😀

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading