与其将HTML转换为带属性的字符串,我需要将其转换回HTML。在Mac上可以轻松完成,如下所示:http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/
不幸的是,方法dataFromRange:documentAttributes:
仅通过NSAttributedString
AppKit附加组件在Mac上可用。
我的问题是如何在iOS上实现这一点?
与其将HTML转换为带属性的字符串,我需要将其转换回HTML。在Mac上可以轻松完成,如下所示:http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/
不幸的是,方法dataFromRange:documentAttributes:
仅通过NSAttributedString
AppKit附加组件在Mac上可用。
我的问题是如何在iOS上实现这一点?
虽然不是“简单”的方法,但可以尝试通过迭代字符串的属性来实现:
- (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]]
编辑:昨天偶然发现了这个:
NSAttributedString+HTMLFromRange类别来自“UliKit” (https://github.com/uliwitness/UliKit/blob/master/NSAttributedString+HTMLFromRange.m)
看起来它能做到你想要的。
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];
DTCoreText
:https://github.com/Cocoanetics/DTCoreText - Joshua