【问题标题】:How to enable UITextView to receive pasted images如何启用 UITextView 接收粘贴的图像
【发布时间】:2016-03-22 03:25:33
【问题描述】:

我需要支持将图像粘贴到UITextView。将图像复制到剪贴板后,“Paste”选项似乎没有弹出。当剪贴板上有文本时会这样做。

这是在自定义UITextView 中覆盖paste 选项的方法。但我需要有关如何获得显示选项的帮助...

// 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?

【问题讨论】:

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


    【解决方案1】:

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

    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
        if (action == @selector(paste:) && [UIPasteboard generalPasteboard].image)
            return YES;
        else
            return [super canPerformAction:action withSender:sender];
    }
    

    不客气。

    【讨论】:

    • 您的代码是正确的,但是在我复制图像后我的粘贴选项没有出现。如何解决这个问题?
    • 您是否记得将 UITextView 设置为您使用此代码创建的自定义类的实例?
    • @MattKoala 谢谢你的回答很完美。
    【解决方案2】:

    感谢@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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 2021-07-03
      • 2014-03-19
      • 1970-01-01
      • 2011-01-19
      • 2012-06-09
      相关资源
      最近更新 更多