Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...