I want to dynamically deliver content and display hyperlinks, but it can’t be delivered dynamically and doesn’t work
let linkTitle = "Apple Link"
let linkURL = "http://www.apple.com"
let string = "[Apple Link](http://www.apple.com)"
Text(string) // Not working
Text("[Apple Link](http://www.apple.com)") // Working
Text("[\(linkTitle)](http://www.apple.com)") // Working
Text("[\(linkTitle)](\(linkURL))") // Not working
Wrap the string in AttributedString(markdown: my_string_here)
:
let string: String = "[Apple Link](http://www.apple.com)"
Text(try! AttributedString(markdown: string))
extension String {
func toMarkdown() -> AttributedString {
do {
return try AttributedString(markdown: self)
} catch {
print("Error parsing Markdown for string \(self): \(error)")
return AttributedString(self)
}
}
}
SwiftUI Text
has multiple initializers.
For String
:
init<S>(_ content: S) where S : StringProtocol
For AttributedString
:
init(_ attributedContent: AttributedString)
When you declare a static string, Swift is able to guess whether the intent is to use a String
or AttributedString
(Markdown). However, when you use a dynamic string, Swift needs help in figuring out your intent.
As a result, with a dynamic string, you have to explicitly convert your String
into an AttributedString
:
try! AttributedString(markdown: string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With