我为NSAttributed设置了一个UITextView字符串(来自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,所以我使用:
- (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,但这不是我想要的。所有的东西都有一个class属性,它放在文档顶部的CSS。像图片和链接这样的东西甚至没有包含在返回的HTML中,而且可能还有很多问题。
从NSAttributedString**?获取是否有更好的方法?或者,我是否可以解析** NSAttributedString 并编写自己的HTML?
发布于 2014-02-05 16:40:19
也许你可以看看那个存储库:https://github.com/IdeasOnCanvas/Ashton
有两个有趣的课程:
AshtonHTMLReader.h
- (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;作者:
AshtonHTMLWriter.h
- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;生成的html不是很好,但是如果您试图在uiwebview中显示它,它看起来很不错。
图像的简单概念:用base64对其进行编码,并将其直接放入带有正确帧的< img >标记中。
它很难看,但是它可以工作,=> --几个月前,我用这个过程创建和编辑了一些html文件
发布于 2014-02-04 18:42:02
这是一个复杂的问题,我将从一个简短的答案开始。你可以在评论中问我一些问题,我会在需要时详述答案。
我们还尝试使用属性化字符串路由,但发现它不适合完整的HTML编辑。许多元素只是不受支持,要么是因为转换器没有得到充分开发,要么是这些元素被苹果公司认为超出了范围。解析属性字符串不够好,因为在尝试重新创建属性字符串时,属性字符串已经失去了HTML的大部分丰富性。
相反,我们使用webview,正常加载文档,并在body元素上启用contentEditable。这样做是允许对文档进行最全面的编辑,仅受WebKit的限制。最后,为了检索返回的HTML,我们禁用了contentEditable,并使用document.outerHTML获得了以前的整个HTML,并进行了用户的更改。
不要轻率地决定实现这个方法。这是一个有点复杂的解决办法,但肯定是可能的。一个网络视图不如文本视图好,但它可以,给予足够的按摩。
我会在有需要时详述这个问题。
发布于 2016-10-03 13:00:19
在我的一个项目中,我还必须将NSAtttributedString转换为HTML。这样做的代码如下所示
//self.attributed String is the attributedString
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [self.attributedString dataFromRange:NSMakeRange(0, self.attributedString.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
NSLog(@"%@", htmlString);https://stackoverflow.com/questions/20309606
复制相似问题