gpt4 book ai didi

iphone - 在 iOS 中将 HTML 转换为 NSAttributedString

转载 作者:行者123 更新时间:2023-11-28 08:11:58 34 4
gpt4 key购买 nike

我正在使用 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com