我希望让我的用户将他们输入的文本复制到剪贴板中,但我希望以HTML格式进行。这种事情是否可能?还是我需要使用MIME格式?(我不知道。)
谢谢。
我希望让我的用户将他们输入的文本复制到剪贴板中,但我希望以HTML格式进行。这种事情是否可能?还是我需要使用MIME格式?(我不知道。)
谢谢。
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/
#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}];
它使用来自RegexKitLite的-stringByReplacingOccurrencesOfRegex:
来去除HTML标签。
我非常喜欢这种创建基于HTML的内容并将其粘贴到其他HTML感知应用程序(如Mail)中的方法。然而,我注意到Matthew Elton提供的解决方案只允许将剪贴板粘贴到HTML感知应用程序中。例如,尝试将完全相同的内容粘贴到Notes应用程序中会失败。
我从这篇文章中获得了一些技巧:https://dev59.com/kHNA5IYBdhLWcg3wQ7Yw#1078471,现在我可以成功地粘贴所需内容的HTML和纯文本版本。
我使用w3schools。 我将我的HTML代码剪切并粘贴到他们的示例代码上,在他们众多的“尝试自己”教程中,然后使用他们的“运行”按钮。
plain
在方法结束时是否具有正确的纯文本表示形式? - Ortwin Gentz