How to paste rich text into a UITextView?

2020-02-11 07:56发布

问题:

My app allows users to format text in a UITextView by clicking some formatting buttons that apply attributes to the attributedText property of the text view. I want to allow users to copy their formatted text from one UITextView and paste it into another using the standard pasteboard and standard cut/copy/paste menu.

Currently if I copy formatted text from a UITextView and paste it into a new message in the Mail app, the formatting is preserved -- so the copying of formatted text is happening automatically. But if I paste the formatted text into another UITextView in my app, only the plain text appears.

By following the "Pasting the Selection" section in the Text Programming Guide for iOS, I was able to override the paste method of UITextView and intercept the pasted content:

- (void)paste:(id)sender {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSLog(@"types available: %@", [pasteboard pasteboardTypes]);
    for (NSString *type in [pasteboard pasteboardTypes]) {
        NSLog(@"type %@ (%@): %@", type, NSStringFromClass([[pasteboard valueForPasteboardType:type] class]), [pasteboard valueForPasteboardType:type]);
    }
}

This shows me that the pasteboard contains content in the following formats: com.apple.rtfd, public.rtf, public.text and "Apple Web Archive pasteboard type". The value for the text is a plain text string, the value for the rtf is an RTF string and the values for the two Apple formats are NSData.

This is where I'm stuck. How can I translate one of these items from the pasteboard data to an attributed string to set for the UITextView?

Or better yet, is there a way to configure the UITextView to accept formatted text automatically when pasting, in the same way that it supplies formatted text automatically when copying?

回答1:

Duncan asked above, "Are you sure you have the uitextview set to handle rich text." I wasn't aware of a setting for that, but I checked the UITextView class reference again and found the allowsEditingTextAttributes property. I hadn't used that before because I was providing my own formatting buttons and didn't need to enable the system Bold/Italic/Underline options. But when I set that property to YES for my UITextView, then it started accepting formatted text automatically. Whew!