【问题标题】:What Happened to NSAttributedString in Swift 5? Bold Doesnt work?Swift 5 中的 NSAttributedString 发生了什么?粗体不起作用?
【发布时间】:2022-10-07 18:32:24
【问题描述】:

我遇到的所有示例代码都不再适用于粗体标签。这也包括斜体 html 标签。

我正在使用来自 hacking 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 样式系统硬编码字体技巧,但效果不佳。

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

    标签: swift swiftui attributedstring


    【解决方案1】:

    请注意,您的 htmlString 属性本质上是将属性字符串转换回纯文本字符串。访问NSAttributedString.string 属性可以返回字符串的纯文本部分,没有任何属性。

    由于此字符串将显示在 Text 中,因此您可以改用 Swift AttributedString API。将htmlAttributedString的类型更改为AttributedString,并转换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

    Text("<b>foo</b>bar".htmlAttributedString)
    

    旁注:如果您使用的是降价,您可以使用这样的字符串文字直接创建Text - 不需要任何AttributedStrings

    Text("**foo** bar")
    

    如果您的降价字符串不是文字,请将其包装在 LocalizedStringKey 中:

    Text(LocalizedStringKey(someMarkdown))
    

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 2016-11-04
      • 1970-01-01
      • 2013-11-04
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      相关资源
      最近更新 更多