使用 HTML 代码后,NSAttributedString 不适用于 UILabel

NSAttributedString not working for UILabel after using HTML code

我有 UILabel,我正在分配 html 文本如下。

m014.text = [NSString stringWithFormat:@"<html><head><style type='text/css'>body {background-color: transparent;border: 0px;margin: 0px;padding: 0px;font-family: '%@'; font-size: %fpx;;ccolor:;}</style></head><body dir='%@'>%@<style type='text/css'> iframe { width: 100%% !important; } img {width: 100%% !important; height: auto;} table {width: 100%%;}</style></body></html>", localize(@"myFontName"), @16, localize(@"myDir"), m014.text];

m014.attributedText = [[NSAttributedString alloc] initWithData: [m014.text dataUsingEncoding:NSUTF32StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil error: nil];

在 iOS 10 及以下我可以看到普通文本(纯文本)但是在 iOS 11 及以上我在应用程序中看到 html 文本。我按原样看到了 html 代码...

知道为什么会这样吗?


主要是,我觉得问题出在下面这行。

[m014.text dataUsingEncoding:NSUTF32StringEncoding]

但我记得,我使用 NSUTF32StringEncoding 因为我看到的是编码字符。

在将 HTML 字符串转换为 NSAttributedString 时,您是否尝试过 NSUTF8StringEncoding?

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[yourHTMLString dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                           NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                      documentAttributes:nil error:nil];

我在我的应用程序中使用类似的代码,但使用 NSUTF16StringEncoding,遵循一些其他答案中的提示,例如:NSAttributedString initWithHTML incorrect character encoding?.

感谢@rmaddy在评论中的回答。

我使用的更新代码如下

m014.attributedText = [[NSMutableAttributedString alloc] initWithHTML:
    [m014.text dataUsingEncoding:NSUTF8StringEncoding] 
    options: @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
    NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
    documentAttributes:nil];