2

UITextView から書式設定されたテキスト ( italicなど) をプログラムでコピーして、別のプログラム (メールなど) に貼り付けたときに書式設定が保持されるようにするにはどうすればよいですか? 正しいアプローチは、NSAttributedString をペーストボードにコピーすることだと思います。現在、次の方法で通常の文字列をペーストボードにコピーできます。

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

標準のテキスト選択 Copy メニュー項目を使用して UITextView からテキストを選択してコピーすると、希望どおりに機能することに気付きました。しかし、作成したボタンを介してこれにアクセスする必要があります。

UIResponderStandardEditActionsのCopy メソッドを呼び出すだけでよいのではないかと考えました。以下を使用すると、メールへの貼り付けは書式設定を保持しましたが、結果としてアプリもクラッシュしました。

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

これを行う正しい方法の例は大歓迎です。

PS - NSAttributedString とペーストボードに関連する既存のスレッドがあることは承知していますが、それらはCocoa 用であるか、 UIResponderStandardEditActions Copy メソッドを参照していないか、UITextView 属性の多くが利用可能になった iOS 6 よりも前のようです。

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 から select メソッドを呼び出すことはできますか?

于 2012-10-18T17:26:40.390 に答える