Copy Text with Formatting - iOS 6 NSAttributedString to Pasteboard

拟墨画扇 提交于 2019-12-12 07:16:34

问题


How can I programmatically copy formatted text (e.g. italic) from a UITextView, so that when pasted into another program (e.g. Mail) the formatting will be retained? I'm assuming the correct approach is to copy an NSAttributedString to the pasteboard. Right now, I am able to copy a regular string to the pasteboard via the following:

NSString *noteTitleAndBody = [NSString stringWithFormat:@"%@\n%@", [document title], [document body]];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = noteTitleAndBody;

I noticed that if I select and copy text from my UITextView with the standard text selection Copy menu item, it works as desired. But I need to access this via a button I've created.

I thought perhaps I could just call the UIResponderStandardEditActions Copy method. Using the following, the paste into Mail did retain the formatting, but my app also crashed as a result.

NSMutableAttributedString *noteTitleAndBody = [[NSMutableAttributedString alloc] initWithString:[document title]];
[noteTitleAndBody appendAttributedString:[document body]];
[noteTitleAndBody copy:nil];

Examples of the correct way to do this would be greatly appreciated.

PS - I am aware that there are existing threads related to NSAttributedString and the pasteboard, but they seem to either be for Cocoa, don't reference the UIResponderStandardEditActions Copy method, or predate iOS 6 where many of the UITextView attributes became available.


回答1:


The following will work for whatever textView is currently first responder:

[UIApplication sharedApplication] sendAction:@selector(copy:) to:nil from:self forEvent:nil];

Since my copy button is only accessible when my textView had resigned firstResponder, I had to do a little more:

[self.noteTextView select:self];
self.noteTextView.selectedRange = NSMakeRange(0, [self.noteTextView.text length]);
[[UIApplication sharedApplication] sendAction:@selector(copy:) to:nil from:self forEvent:nil];
[self.noteTextView resignFirstResponder];

Thanks to the following posts which pointed me in the right direction:

Perform copy/cut from UIResponderStandardEditActions

can I call a select method from UIResponderStandardEditActions?



来源:https://stackoverflow.com/questions/12789507/copy-text-with-formatting-ios-6-nsattributedstring-to-pasteboard

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