将字体属性添加到 HTML 渲染的 UILabel swift



我有一些HTML内容,我想在我的原生UILabel中呈现,但除此之外,我必须向该UILabel添加自定义字体。我正在使用NSAttributedString来做到这一点,并使用以下代码在我的UILabel中呈现HTML内容。

 func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: .utf16, allowLossyConversion: false) else {
        return nil
    }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }

    let attributes = [
        NSForegroundColorAttributeName: UIColor.lightGray,
        NSFontAttributeName : UIFont.systemFont(ofSize: 12)
    ]
    html.setAttributes(attributes, range: NSRange(0..<html.length))
    return html
}
var str = "Here is the <bold>string</bold> that i want to be bold.
messageLabel.attributedText = str.htmlAttributedString()

这里的问题是,当我在 HTML 呈现的属性字符串上应用字体属性时。然后所有像粗体这样的HTML格式都会丢失。

那么有没有办法我可以在 HTML 呈现的属性字符串上应用一些选定的字体

根据您的要求替换字体。

func htmlAttriButedText(str : String) -> NSAttributedString{
        let attrStr = try! NSMutableAttributedString(
            data: str.data(using: String.Encoding.utf8, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
        attrStr.addAttribute(NSForegroundColorAttributeName, value: lightTextColor, range: NSMakeRange(0, attrStr.length))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 13), range: NSMakeRange(0, attrStr.length))
        return attrStr
    }

最新更新