在iOS中将HTML转换为NSAttributedString
我使用 UIWebView
的实例来处理一些文本和颜色正确,它给出的结果为HTML,而不是显示在 UIWebView
我想使用核心文本
和 NSAttributedString
显示它。
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.
In iOS 7, UIKit added an initWithData:options:documentAttributes:error: method which can initialize an NSAtttributedString using HTML, eg:
[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];