iphone - 在 iOS 中将 HTML 转换为 NSAttributedString

标签 iphone objective-c cocoa-touch core-text nsattributedstring

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

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

我知道在 Mac OS X 下 NSAttributedString 有一个 initWithHTML: 方法,但这只是 Mac 的补充,不适用于 iOS。

我也知道有一个类似的问题,但没有答案,我想再试一次,看看是否有人创造了一种方法来做到这一点,如果有,他们是否可以分享。

最佳答案

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

[[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)

关于iphone - 在 iOS 中将 HTML 转换为 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43507264/

相关文章:

iphone - 为 UITableViewController 子类调用 loadView

ios - 如何访问 objective-c 文件中的swift公共(public)函数?

Objective-C:将实现协议(protocol)的类别添加到现有类是否会使对象符合该协议(protocol)?

iPhone 音频服务播放系统声音 : route though headphones?

ios - 为什么在尝试向上滚动表格时我的 UITableView 内容为 'jump up'?

iphone - 使用 loadHTMLString 在 drawRect 中渲染 UIWebView

iphone - UITableViewCell 分隔符未显示

ios - iPhone 连接到 localhost Rails sarver

ios - 来自 Objective-C 的可选协议(protocol)不是应该在 Swift 中完成的事情吗?

ios - iOS6 中的社交分享面板