在 iOS 中将 HTML 转换为 NSAttributedString

在 iOS 中将 HTML 转换为 NSAttributedString

问题描述:

我正在使用 UIWebView 的一个实例来处理一些文本并正确地给它上色,它以 HTML 形式给出结果,而不是在我想要的 UIWebView 中显示它使用带有 NSAttributedStringCore Text 显示它.

I am using a instance of UIWebView to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the UIWebView I want to display it using Core Text with a NSAttributedString.

我能够创建和绘制 NSAttributedString,但我不确定如何将 HTML 转换并映射到属性字符串中.

I am able to create and draw the NSAttributedString but I am unsure how I can convert and map the HTML into the attributed string.

我知道在 Mac OS X 下 NSAttributedString 有一个 initWithHTML: 方法,但这只是 Mac 的附加功能,不适用于 iOS.

I understand that under Mac OS X NSAttributedString has a initWithHTML: method but this was a Mac only addition and is not available for iOS.

我也知道有一个与此类似的问题,但没有答案,不过我会再试一次,看看是否有人已经创建了一种方法来做到这一点,如果有,他们是否可以分享.

I also know that there is a similar question to this but it had no answers, I though I would try again and see whether anyone has created a way to do this and if so, if they could share it.

在 iOS 7 中,UIKit 添加了一个 initWithData:options:documentAttributes:error: 可以使用 HTML 初始化 NSAttributedString 的方法,例如:

In iOS 7, UIKit added an initWithData:options:documentAttributes:error: method which can initialize an NSAttributedString using HTML, eg:

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

在 Swift 中:

let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
        NSAttributedString.DocumentType.html]
let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
                                                          options: options,
                                                          documentAttributes: nil)