在 iOS 中将 HTML 转换为 NSAttributedString [英] Convert HTML to NSAttributedString in iOS

查看:41
本文介绍了在 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)

这篇关于在 iOS 中将 HTML 转换为 NSAttributedString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆