在 Cocoa 中打开 HTML 源代码
我正在尝试在基于 NSDocument 的应用程序中显示 HTML 源代码。但是,它会按照 Safari 的显示方式呈现页面。
这是我用来打开 HTML 的代码:
NSData*data;
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType
forKey:NSDocumentTypeDocumentOption];
data = [NSData dataWithContentsOfFile:[self fileName]];
mString = [[NSAttributedString alloc]
initWithData:data options:dict documentAttributes:NULL
error:outError];
我做错了什么?
I'm trying to display HTML source code in my NSDocument based application. However, it renders the page as Safari would show it.
Here's the code that I use to open HTML:
NSData*data;
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType
forKey:NSDocumentTypeDocumentOption];
data = [NSData dataWithContentsOfFile:[self fileName]];
mString = [[NSAttributedString alloc]
initWithData:data options:dict documentAttributes:NULL
error:outError];
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的解决方案是您的原始代码和我在之前的答案中给您的虚假解决方案(我已删除)的混合。使用
NSPlainTextDocumentType
作为类型,就像您最初所做的那样,但使用initWithData:options:documentAttributes:error:
,而不是initWithHTML:options:documentAttributes:
>。或者,创建一个保存源代码的纯 NSString,然后使用该纯字符串加上您想要应用于整个文档的任何属性(例如,固定间距字体)创建一个属性字符串。
The correct solution is a mix of your original code and the bogus solution I gave you in my previous answer (which I've deleted). Use
NSPlainTextDocumentType
as the type, as you were doing originally, but useinitWithData:options:documentAttributes:error:
, notinitWithHTML:options:documentAttributes:
.Alternatively, create a plain NSString holding the source code, and then create an attributed string with that plain string plus whatever attributes you want to apply to the whole document (e.g., fixed-pitch font).