【问题标题】:HTML from NSAttributedString来自 NSAttributedString 的 HTML
【发布时间】:2011-07-03 17:05:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: html objective-c ios nsattributedstring


    【解决方案1】:

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

    - (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)

    看起来它会做你想做的。

    【讨论】:

    • 是的,我正在考虑。最困难的部分是处理字体以查看它们是粗体、斜体还是没有。我现在可以试一试,看看效果如何。谢谢!
    • 太好了,刚刚注意到新链接(SO 似乎在编辑答案时没有通知),它可以满足我的一切需求。非常感谢! (+1 & ✔)
    • @Joshua 这如何解决您的问题?似乎 NSAttributedString+HTMLFromRange 充满了 OS X 专用的东西,不是吗?
    • @MatthewFrederick 我从来没有继续使用它来实现任何东西,但我记得最后看到的是 Cocoanetics DTCoreText。它只是为了从 HTML 中获取 NSAttributedString,现在支持反过来,即从 NSAttributedString 中获取 HTML。你可以在 Github 上找到DTCoreTextgithub.com/Cocoanetics/DTCoreText
    • 对于其他需要 Joshua 所说的内容的人,here。它在 DTCoreText 中,由于某种原因我找不到它,但现在我有了 :)
    【解决方案2】:

    使用下面的代码。效果很好。

    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];
    

    【讨论】:

    • 这可行,但它创建的是 HTML 4 格式而不是 HTML 5。
    猜你喜欢
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多