Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste rich text into a UITextView?

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?

like image 274
arlomedia Avatar asked Dec 26 '22 17:12

arlomedia


1 Answers

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!

like image 178
arlomedia Avatar answered Jan 11 '23 05:01

arlomedia