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*")
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?
CodePudding user response:
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! :D