来自NSAttributedString的HTML [英] HTML from NSAttributedString

查看:98
本文介绍了来自NSAttributedString的HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与其将HTML转换为属性字符串,我需要将其转换回HTML。这可以很容易地在Mac上完成,如下所示: http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/
$ b $不幸的是,方法 dataFromRange:documentAttributes:只能在Mac上通过 NSAttributedString AppKit Additions



我的问题是如何在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

看起来它会做你想做的。


Rather than converting HTML to an attributed string, I need to convert it back to HTML. This can easily be done on Mac as can be seen here: http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/

Unfortuately, the method dataFromRange:documentAttributes: is only available on Mac via the NSAttributedString AppKit Additions.

My question is how can you do this on iOS?

解决方案

Not the 'easy' way, but what about iterating through the attributes of the string using:

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

Have an NSMutableString variable to accumulate the HTML (lets call it 'html'). In the block, you would construct the HTML manually using strings. For instance if the text attributes 'attrs' specify red, bold text:

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


EDIT: Stumbled across this yesterday:

NSAttributedString+HTMLFromRange category from "UliKit" (https://github.com/uliwitness/UliKit/blob/master/NSAttributedString+HTMLFromRange.m)

Looks like it will do what you want.

这篇关于来自NSAttributedString的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆