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>
    <html>
    <head>
    <style type='text/css'>
    body {
        font-family: '\(fontFamily)';
        font-size: \(fontSize)px;
        color: \(convertedFontColor);
        margin: 0px;
        padding: 0px;
        text-align: \(alignment);
    };
    </style>
    </head>
    <body>\(htmlText)</body>
</html>
"""

let encodedData = html.data(using: 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?

问题评论:

答案:

答案1:

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;

答案评论:

原文地址:

https://stackoverflow.com/questions/47755574/show-html-text-in-nsattributedstring-with-system-font-bold-tag-is-not-working

添加评论

友情链接:蝴蝶教程