简体   繁体   中英

Setting font in html for UILabel attributed text is not working

Html text with font-size or setting UIFont on UILabel is making the NSAttributedText to not render properly.

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

This is not rendering bold. Same issue if I try to set the font manually to the label. How to fix this?

In the html text that you are using, the span tag is not closed.

Try changing the value of lbl.attributedText to:

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

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM