Question

When I implement the following code to copy text in an NSTextView object by way of an action and then manually paste it into something like a text editor or an email client, the pasted text is one long string.

How do I retain the formatting of the text?

Thanks.

NSString *string = [outputText string];

NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
[pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
[pasteBoard setString:string forType:NSStringPboardType]
Was it helpful?

Solution

You don't need to do anything to implement copying of NSTextView text. NSTextView is a subclass of NSText and inherits the copy: method.

To copy the current text selection to the clipboard, just call [yourTextView copy:self];.

As explained in the docs, if your text view is set to allow rich text, then the clipboard will contain a plain string (NSStringPboardType) and an attributed string (NSRTFPboardType).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top