请注意,您的
htmlString
属性将属性化字符串转换回纯文本字符串。访问
NSAttributedString.string
属性返回字符串的纯文本部分,不带任何属性。
由于此字符串将显示在
Text
,您可以使用Swift
AttributedString
而是API。更改的类型
htmlAttributedString
到
属性字符串
,并将
NSAttributedString
:
extension String {
var htmlAttributedString: AttributedString {
if let attributedString = try? NSAttributedString(data: Data(self.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return AttributedString(attributedString)
}
else {
return ""
}
}
}
然后您可以创建
文本
这样地:
Text("<b>foo</b>bar".htmlAttributedString)
旁注:如果您改为使用降价,则可以直接创建
文本
使用这样的字符串文字-不需要任何
属性字符串
s
Text("**foo** bar")
如果标记字符串不是文本,请将其包装在
LocalizedStringKey
:
Text(LocalizedStringKey(someMarkdown))