Copy NSAttributedString to pasteboard

冷暖自知 提交于 2019-12-17 19:42:57

问题


Brand new to Cocoa and I'm trying to figure out how to copy an NSAttributedString to the pasteboard. I've looked in the docs and not sure if I'm supposed to use a NSPasteboardItem or not.

Here's what I have to copy a regular NSString:

NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
[pb declareTypes:types owner:self];

[pb setString:@"asdfasdf" forType:NSStringPboardType];

How do I set a NSAttributedString?

Thanks


回答1:


You want either NSRTFPboardType or NSRTFDPboardType along with the NSAttributedString's RTFFromRange:documentAttributes:/RTFDFromRange:documentAttributes: and setData on the pasteboard.




回答2:


As of Snow Leopard, NSAttributedString (when powered up by AppKit) conforms to NSPasteboardWriting, so you can simply do this:

[pb clearContents];
[pb writeObjects:arrayOfAttributedStrings];

You can send NSArray an arrayWithObject: message if you have only one attributed string you want to put on the pasteboard.

[Edit from the year 2013: Or use the shiny new @[ myAttributedString ] syntax. Works for any number of objects, although they still need to all conform to NSPasteboardWriting in this context.]

This goes for NSString as well. Search the AppKit headers for “NSPasteboardWriting” to find all of the standard Cocoa classes that support it.




回答3:


NSPasteboard *paste = [NSPasteboard generalPasteboard];  
[paste clearContents];      
[paste declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
NSMutableAttributedString *aString;// init some string
BOOL success =  [paste writeObjects:[NSArray arrayWithObject:aString]];


来源:https://stackoverflow.com/questions/2581407/copy-nsattributedstring-to-pasteboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!