来自 NSAttributedString 的 HTML

标签 html objective-c ios nsattributedstring

我需要将其转换回 HTML,而不是将 HTML 转换为属性字符串。这可以在 Mac 上轻松完成,如下所示:http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/

不幸的是,dataFromRange:documentAttributes: 方法只能通过 NSAttributedString AppKit Additions 在 Mac 上使用。

我的问题是如何在 iOS 上执行此操作?

最佳答案

这不是“简单”的方法,而是使用以下方法遍历字符串的属性:

- (void)enumerateAttributesInRange:(NSRange)enumerationRange 
                           options:(NSAttributedStringEnumerationOptions)opts 
                        usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block

有一个NSMutableString变量来累积 HTML(我们称之为“html”)。在该 block 中,您将使用字符串手动构建 HTML。例如,如果文本属性“attrs”指定红色、粗体文本:

[html appendFormat:@"<span style='color:red; font-weight: bold;'>%@</span>", [originalStr substringWithRange:range]]


编辑:昨天偶然发现了这个:

来自“UliKit”的 NSAttributedString+HTMLFromRange 类别 ( https://github.com/uliwitness/UliKit/blob/master/NSAttributedString+HTMLFromRange.m )

看起来它会做你想做的事。

关于来自 NSAttributedString 的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6564258/

相关文章:

ios - imageView 无法连接到 Objective-C 中 IBOulet 的头文件

javascript - IE中的CSS翻转动画: Turned side shows mirror content

html - 为什么 align-content/align-items 在这里不起作用?

objective-c - 如何从 firebase 数据库读取一小节

ios - 在 iOS 中添加 UIButtons 数组

iphone - 每次在 UITabBarBased 应用程序中单击选项卡栏项目时,如何显示不同的 View ?

javascript - Bootstrap 选择器显示 :Uncaught TypeError: Cannot set property '_menu' of undefined

html - 通过以列方式设置数据从 REST 对象创建表

ios - 无法在自定义表格 View 单元格上设置属性

ios - 无互联网连接时的 URLSession 响应