2

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

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

我注意到,如果我使用标准文本选择“复制”菜单项从 UITextView 中选择并复制文本,它会按需要工作。但我需要通过我创建的按钮来访问它。

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

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

将不胜感激正确方法的示例。

PS - 我知道存在与 NSAttributedString 和粘贴板相关的现有线程,但它们似乎要么用于 Cocoa不引用 UIResponderStandardEditActions Copy 方法,要么早于 iOS 6,其中许多 UITextView 属性可用。

4

1 回答 1

1

以下内容适用于当前作为第一响应者的任何 textView:

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

因为我的复制按钮只有在我的 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];

感谢以下帖子为我指明了正确的方向:

从 UIResponderStandardEditActions 执行复制/剪切

我可以从 UIResponderStandardEditActions 调用选择方法吗?

于 2012-10-18T17:26:40.390 回答