如何启用UITextView来接收粘贴的图像

时间:2015-12-16 05:21:04

标签: ios objective-c cocoa-touch uitextview uimenucontroller

我需要支持将图片粘贴到UITextView中。将图像复制到剪贴板后," Paste"选项似乎不会弹出。当剪贴板上有文字时就会这样做。

这是覆盖自定义paste中的UITextView选项的方法。但是我需要帮助才能让选项显示出来......

// This gets called when user presses menu "Paste" option
- (void)paste:(id)sender{

    UIImage *image = [UIPasteboard generalPasteboard].image;

    if (image) {
        NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
        textAttachment.image = image;
        NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:textAttachment];
        self.attributedText = imageString;
    } else {
        // Call the normal paste action
        [super paste:sender];
    }
}

我遇到了一些相关问题,但对于像我这样缺乏经验的开发人员来说,它们并没有帮助: How to get UIMenuController work for a custom view?How to paste image from pasteboard on UITextView?

2 个答案:

答案 0 :(得分:8)

我回答了自己的问题。您所要做的就是通过覆盖此UITextView方法让UITextView说“我可以接收粘贴的图像”:

render()

欢迎你。

答案 1 :(得分:0)

谢谢@Matt 你的回答帮助了我。只是扩展您的答案可能会对某些人有所帮助,

继承 UITextview,当粘贴板中有图像时,长按显示粘贴选项。

class MyTextView:UITextView {
    var onPasteImage:(()->Void)?
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(paste(_:)) && UIPasteboard.general.image != nil {
            return true
        }else{
            return super.canPerformAction(action, withSender: sender)
        }
    }
    
    override func paste(_ sender: Any?) {
        super.paste(sender)
        if UIPasteboard.general.image != nil {
            onPasteImage?()
        }
    }
}

等待 onPasteImage 闭包在 textview 中点击粘贴时被调用,

inputFieldForReply.textView.onPasteImage = { [weak self] in
    if let image = UIPasteboard.general.image {
        // Process pasted image
    }
}