How to paste image from pasteboard on UITextView?

前提是你 提交于 2019-11-28 11:42:49
Aaron Brager

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.

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
}
Nikos M.

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