Show HTML text in NSAttributedString with System Font – Bold tag is not working


I have texts with HTML tags, e.g.:

This is a text with some <b>bold</b> part. 

We have an NSAttributedString extension where we put this text in an HTML body and setting other properties like font size, font family, color etc., and I set this HTML text for NSAttributedString. Here is the example code:

let htmlText = "This is a text with some <b>bold</b> part"
let fontFamily = UIFont.systemFont(ofSize: 20).familyName // Value of fontFamily: ".SF UI Display"

let html = """
<!DOCTYPE html>
    <style type='text/css'>
    body {
        font-family: '\(fontFamily)';
        font-size: \(fontSize)px;
        color: \(convertedFontColor);
        margin: 0px;
        padding: 0px;
        text-align: \(alignment);

let encodedData = String.Encoding.utf8)!
let attributedOptions: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
    NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)

let attributedString = (try? NSAttributedString(data: encodedData,
                                                options: attributedOptions,
                                                documentAttributes: nil))

As long as I use custom fonts, it works well; but if I want to use the system font as in the example above, the bold tags are ignored and all the text looks like the same without setting the bold part.

It looks like in case of systemFont, it does not work to have some part of the text bold in this way, also, the family name of the system font is weird: .SF UI Display

Anyone has any idea how could I show HTML formatted text with bold parts using the system font?




The font family name used in CSS is not the same as the familyName of a UIFont, it’s not a good idea to merge the two.

For an easy solution, you can use the system font by simply using sans-serif as font-family in your CSS:

font-family: sans-serif;



Add a Comment