NSAttributedString 不会显示正确的字体

NSAttributedString won't show correct font

通过这个 NSAttributedString 函数,我有一个显示 HTML 的标签。 问题是我想给它添加自定义字体,但是它没有添加字体。

我做错了什么?

这是我的代码:

extension String {
    func convertHtml() -> NSAttributedString {
        let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)

        }catch{
            return NSAttributedString.init(string: self, attributes: titleAttributes)
        }
    }
}

如果您希望替换生成的 HTML 中的所有字体设置,您需要在从 HTML 字符串创建属性字符串后应用您的 titleAttributes

extension String {
    func convertHtml() -> NSAttributedString {
        let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            let res = try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
            let mutable = res.mutableCopy() as! NSMutableAttributedString
            mutable.addAttributes(titleAttributes, range: NSRange(location: 0, length: res.length))

            return mutable
        }catch{
            return NSAttributedString.init(string: self, attributes: titleAttributes)
        }
    }
}