7

我有兴趣让我的用户将他们输入的文本复制到剪切和粘贴缓冲区中,但我想将其作为 HTML 进行。

这样的事情甚至可能吗?还是我需要使用 MIME 格式?(我不知道。)

谢谢。

4

4 回答 4

7

以下代码将把您的 HTML 从您的应用程序中取出并放入 Apple 的邮件应用程序。文档在这方面并没有为您提供很多帮助,因此部分原因在于查看 Apple 的应用程序在粘贴板上停放的内容,然后对其进行逆向工程。此解决方案借鉴了早期的stackoverflow 帖子- 跟进那里的链接以获取更多背景信息。

NSLog(@"Place HTML on the pasteboard");

UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
NSString *htmlType = @"Apple Web Archive pasteboard type";

// example html string
NSString* htmlString = @"<p style=\"color:gray\"> <a href=@\"http://itunes.apple.com/gb/app/paragraft/id412998778?mt=8\">Paragraft</a><br><em>Less than a word processor, more than plain text</em>";

NSMutableDictionary *resourceDictionary = [NSMutableDictionary dictionary];    

[resourceDictionary setObject:[htmlString dataUsingEncoding:NSUTF8StringEncoding]  forKey:@"WebResourceData"];

[resourceDictionary setObject:@"" forKey:@"WebResourceFrameName"];
[resourceDictionary setObject:@"text/html" forKey:@"WebResourceMIMEType"];
[resourceDictionary setObject:@"UTF-8" forKey:@"WebResourceTextEncodingName"];
[resourceDictionary setObject:@"about:blank" forKey:@"WebResourceURL"];

NSDictionary *containerDictionary = [NSDictionary dictionaryWithObjectsAndKeys:resourceDictionary, @"WebMainResource", nil];

NSDictionary *htmlItem = [NSDictionary dictionaryWithObjectsAndKeys:containerDictionary,htmlType,nil];

[pasteboard setItems: [NSArray arrayWithObjects: htmlItem, nil]];

// This approach draws on the blog post and comments at:
// http://mcmurrym.wordpress.com/2010/08/13/pasting-simplehtml-into-the-mail-app-ios/
于 2011-07-04T02:37:08.170 回答
4

此解决方案将 HTML 和纯文本表示形式都放入粘贴板:

#import <MobileCoreServices/MobileCoreServices.h>

NSString *html = @"<h1>Headline</h1>text";
NSData *data =  [html dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = @{@"WebMainResource": @{@"WebResourceData": data, @"WebResourceFrameName": @"", @"WebResourceMIMEType": @"text/html", @"WebResourceTextEncodingName": @"UTF-8", @"WebResourceURL": @"about:blank"}};
data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:nil];
NSString *archive = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *plain = [html stringByReplacingOccurrencesOfRegex:@"<[^>]+>" withString:@""];
[UIPasteboard generalPasteboard].items = @[@{@"Apple Web Archive pasteboard type": archive, (id)kUTTypeUTF8PlainText: plain}];

它使用-stringByReplacingOccurrencesOfRegex:RegexKitLite去除HTML 标签。

于 2012-11-27T13:36:29.183 回答
0

我非常喜欢这种创建基于 HTML 的内容的方法,您可以将这些内容粘贴到其他支持 HTML 的应用程序中,例如 Mail。但是,我注意到Matthew Elton的上述解决方案只允许将粘贴板粘贴到支持 HTML 的应用程序上。例如,尝试将完全相同的内容粘贴到 Notes 应用程序中会失败。

我从这篇文章中得到了提示:https ://stackoverflow.com/a/1078471/351810现在可以成功粘贴我想要的内容的 HTML 和纯文本版本。

于 2012-02-27T14:49:56.383 回答
-1

我使用 w3schools。我将我的 html 代码剪切并粘贴到他们的示例代码上,在他们的许多“自己尝试”教程中的任何一个上,然后使用他们的“运行”按钮。

例如https://www.w3schools.com/html/default.asp

于 2020-02-29T10:05:58.780 回答