用格式复制文本 – iOS 6将NSAttributedString复制到粘贴板

我如何以编程方式从UITextView复制格式化文本(例如斜体 ),以便粘贴到另一个程序(例如邮件)格式将被保留? 我假设正确的做法是将NSAttributedString复制到粘贴板。 现在,我可以通过以下方式将常规string复制到粘贴板:

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

我注意到,如果我从标准文本select“复制”菜单项从我的UITextView中select和复制文本,它将按需要工作。 但我需要通过我创build的button访问这个。

我想也许我可以调用UIResponderStandardEditActions复制方法。 使用以下内容,粘贴到邮件确实保留格式,但我的应用程序也因此崩溃。

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

正确的方法来做到这一点的例子将不胜感激。

PS – 我知道现在有与NSAttributedString和粘贴板相关的线程,但它们似乎是Cocoa , 不参考UIResponderStandardEditActions复制方法 ,或早于iOS 6许多UITextView属性可用。

以下将适用于任何textView目前第一响应者:

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

由于我的复制button只有当我的textView辞职firstResponder时才能访问,所以我不得不多做一点:

 [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]; 

感谢以下post指出我正确的方向:

从UIResponderStandardEditActions执行复制/剪切

我可以从UIResponderStandardEditActions调用select方法吗?