iOS NSAttributedString为HTML

Nic*_*ard 23 objective-c uitextview nsattributedstring ios textkit

我有一个NSAttributed字符串(来自HTML)我设置为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;

}
Run Code Online (Sandbox Code Playgroud)

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

- (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];
}
Run Code Online (Sandbox Code Playgroud)

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

有没有更好的方法来获取HTML NSAttributedString?或者,有没有办法解析NSAttributedString并编写自己的HTML?

Alb*_*ban 12

也许你可以看看那个存储库:https: //github.com/IdeasOnCanvas/Ashton

有2个有趣的课程:

AshtonHTMLReader.h

 - (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;
Run Code Online (Sandbox Code Playgroud)

而作者:

AshtonHTMLWriter.h

- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;
Run Code Online (Sandbox Code Playgroud)

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

图像的简单构思:使用base64对其进行编码,并将其直接放在带有右框架的<img>标签中.

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


Leo*_*ica 9

这是一个复杂的问题,我将从较短的答案开始.您可以在评论中问我问题,我会根据需要扩展答案.

我们还尝试使用属性字符串路由,但发现它不适合完整的HTML编辑.许多元素都不受支持,因为转换器尚未完全开发,或者Apple认为这些元素超出了范围.解析属性字符串是不够的,因为在您尝试重新创建它时,属性字符串已经丢失了HTML的大部分丰富内容.

相反,我们使用webview,正常加载文档,并contentEditable在body元素上启用.这样做可以最大限度地编辑文档,仅受WebKit的限制.最后,为了检索HTML,我们禁用contentEditabledocument.outerHTML获取以前的整个HTML,并使用用户进行的更改.

不要轻易地决定实施这种方法.这是一个有点复杂的解决方案,但肯定是可能的.webview不如textview那么好,但是可以给予足够的按摩.

我会根据需要扩展这个答案.