代码之家  ›  专栏  ›  技术社区  ›  chitgoks

Swift 5中的NSAttributedString发生了什么?大胆不起作用?

  •  0
  • chitgoks  · 技术社区  · 2 年前

    我使用黑客swift的代码作为字符串扩展。

    var htmlAttributedString: NSAttributedString? {
            if let attributedString = try? NSAttributedString(data: Data(self.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
                return attributedString
            }
            else {
                return nil
            }
        }
        
        var htmlString: String {
            return htmlAttributedString?.string ?? ""
        }
    

    let string = "<b>sample</b>"
    Text(string.htmlString)
    

    代码看起来很正确。只是粗体标记没有被呈现。有人知道变通方法吗?我尝试了添加html风格的系统硬编码字体技巧,但效果不佳。

    我尝试了降价替代方案,但也没有运气(但这是一个不同的主题)。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Sweeper    2 年前

    请注意,您的 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))
    
    推荐文章