How to paste rich text into a UITextView?

好久不见. 提交于 2019-11-30 08:49:19

问题


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!



来源:https://stackoverflow.com/questions/20210181/how-to-paste-rich-text-into-a-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!