11

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

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

我的问题是如何在 iOS 上做到这一点?

4

2 回答 2

7

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

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

有一个NSMutableString变量来积累 HTML(我们称之为“html”)。在该块中,您将使用字符串手动构建 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

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

于 2011-07-04T01:42:02.653 回答
1

使用下面的代码。它运作良好。

NSAttributedString *s = ...;
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute:    NSHTMLTextDocumentType};    
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length)    documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
于 2016-07-21T05:37:47.883 回答