How to paste image from pasteboard on UITextView?

前端 未结 3 1731
心在旅途
心在旅途 2020-12-10 19:49

I have the following code on a keyboard extensión

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


        
相关标签:
3条回答
  • 2020-12-10 20:26

    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.

    0 讨论(0)
  • 2020-12-10 20:26

    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
    }
    
    0 讨论(0)
  • 2020-12-10 20:30

    Create an NSTextAttachment from the image and an attributed string with the TextAttachment. Then set the attributedText property of the UITextView. Subclass UITextView and override the paste(_:) method:

    override func paste(_ sender: Any?) {
        let textAttachment = NSTextAttachment()
        textAttachment.image = UIPasteboard.general.image
        attributedText = NSAttributedString(attachment: textAttachment)
    }
    
    0 讨论(0)
提交回复
热议问题