在 html 中为 UILabel 属性文本设置字体无效

Setting font in html for UILabel attributed text is not working

Html 带有 font-size 的文本或在 UILabel 上设置 UIFont 会使 NSAttributedText 无法正确呈现。

extension String {
    var htmlToAttributedLabelString: NSAttributedString? {
        guard let data = NSString(string: self).data(using: String.Encoding.utf8.rawValue) else { return nil }
        do {
            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {}
        return nil
    }
}
let lbl = UILabel()
lbl.attributedText = "<span style=\"font-size: 22px\"; Please read the <b>Nomination Guidelines</b> before completing this form.".htmlToAttributedLabelString

这不是加粗。如果我尝试手动将字体设置为标签,也会出现同样的问题。如何解决这个问题?

在您使用的html text中,span标签没有关闭。

尝试将 lbl.attributedText 的值更改为:

lbl.attributedText = "<span style=\"font-size: 22px\">; Please read the <b>Nomination Guidelines</b> before completing this form.".htmlToAttributedLabelString

输出: