iOS NSAttributedString为HTML [英] iOS NSAttributedString to HTML

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

问题描述

我为 UITextView 设置了 NSAttributed 字符串(来自HTML)。

I have an NSAttributed string (coming from HTML) that I set for a UITextView.

- (void)setHtml:(NSString *)html {

    NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];

    // Create the HTML string
    NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSError *error = nil;
    self.htmlString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];

    self.editorView.attributedText = self.htmlString;

}

然后我让用户编辑他们想要的东西,我我想再将其转换为HTML,所以我使用:

I then let the user edit what they want, and I would like to then convert it out to HTML again, so I use:

- (NSString *)getHTML {
    NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSData *htmlData = [self.editorView.attributedText dataFromRange:NSMakeRange(0, self.editorView.attributedText.length) documentAttributes:exportParams error:nil];
    return [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
}

它确实返回HTML,但这不是我想要的。一切都被赋予了一个类属性,以及它放在文档顶部的CSS。图像和链接等内容甚至不包含在返回的HTML中,可能还有更多问题。

It does return HTML, but it isn't how I want it. Everything is given a class attribute, and the CSS it put at the top of the document. Things like images and links are not even included in the returned HTML and probably tons more issues.

是否有更好的方法从<$ c获取HTML $ C> NSAttributedString ?或者,有没有办法解析 NSAttributedString 并编写自己的HTML?

Is there a better way to get HTML from an NSAttributedString? Or, is there a way I could parse the NSAttributedString and write my own HTML?

推荐答案

您可以查看该存储库:
https:// github .com / IdeasOnCanvas / Ashton

May be you could look at that repository: https://github.com/IdeasOnCanvas/Ashton

有2个有趣的课程:

AshtonHTMLReader.h

 - (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;

作者:

AshtonHTMLWriter.h

- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;

生成的html不是很好但是如果你试图在uiwebview中显示它,
它看起来相当不错。

The html generated isn't very nice but if you try to display it in a uiwebview, it looks pretty good.

图像的简单想法:
用base64对其进行编码并将其直接放在< img>带有正确框架的标签。

Simple idea for image: encode it with base64 and put it directly in a < img > tag with the right frame.

这很难看但它的工作原理=>我几个月前用这个过程来创建和编辑一些html文件

It's ugly but it works => I've used this process to create and edit some html file few month ago

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

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