Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste image from pasteboard on UITextView?

I have the following code on a keyboard extensión

let pasteboard = UIPasteboard.generalPasteboard()
var image = UIImage(named: "myimage");
pasteboard.image = image;

This doesn't work on a UITextView I have on my container application, paste context menu never shows up. It works on other applications like "messages" but not on mine.

My code works if I try to paste text instead of an image using string property so I'm quite near.

I could need to set up my text view different but I don't know how. I've changed "Text" from "Plain" to "Attributed" but still not working.

like image 713
StackOverflower Avatar asked Mar 20 '15 20:03

StackOverflower


Video Answer


2 Answers

It doesn't work if implemented in UITextView subclass, but I tried it in the UIViewController containing the textView and it worked:

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {

    if (action == @selector(paste:)) {
        return [UIPasteboard generalPasteboard].string != nil || [UIPasteboard generalPasteboard].image != nil;
        //if you want to do this for specific textView add && [yourTextView isFirstResponder] to if statement
    }

    return [super canPerformAction:action withSender:sender];

}

-(void)paste:(id)sender {
    //do your action here
}
like image 186
Frane Poljak Avatar answered Oct 15 '22 01:10

Frane Poljak


UITextView only supports pasting text out of the box. You can subclass it and add support for pasting images, which can be implemented using attributed string text attachments.

NSHipster's writeup on UIMenuController and this Stack Overflow question explain the paste logic.

like image 26
Aaron Brager Avatar answered Oct 15 '22 00:10

Aaron Brager