【问题标题】:How to paste image from pasteboard on UITextView?如何将剪贴板中的图像粘贴到 UITextView 上?
【发布时间】:2023-04-08 07:05:01
【问题描述】:

我在键盘扩展上有以下代码

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

这不适用于我的容器应用程序中的UITextView,粘贴上下文菜单永远不会出现。它适用于“消息”等其他应用程序,但不适用于我的。

如果我尝试使用 string 属性粘贴文本而不是图像,我的代码就可以工作,所以我已经很接近了。

我可能需要设置不同的文本视图,但我不知道怎么做。我已将“文本”从“普通”更改为“属性”,但仍然无法正常工作。

【问题讨论】:

    标签: ios ios-extensions


    【解决方案1】:

    从图像和带有 TextAttachment 的属性字符串创建一个NSTextAttachment。然后设置UITextView 的属性文本属性。继承 UITextView 并覆盖 paste(_:) 方法:

    override func paste(_ sender: Any?) {
        let textAttachment = NSTextAttachment()
        textAttachment.image = UIPasteboard.general.image
        attributedText = NSAttributedString(attachment: textAttachment)
    }
    

    【讨论】:

    • mhhh,但是如果“粘贴”上下文菜单从未出现,我该如何触发呢?
    • @TimmyO'Tool 编辑了我的答案。您必须继承 UITextView 并覆盖粘贴功能。
    • 谢谢,我会检查一下。在任何情况下,我都不想粘贴到我的应用程序中,只是想确保我正确实现了复制功能以使其与第三方应用程序一起使用。现在我知道问题在于 UITextView 不支持开箱即用,而不是我的代码中的错误。
    • 我很困惑。 @StackOverflower 的问题的答案是什么,“但是如果‘粘贴’上下文菜单从未出现,我该如何触发呢?”
    【解决方案2】:

    如果在 UITextView 子类中实现它不起作用,但我在包含 textView 的 UIViewController 中尝试了它并且它起作用了:

    -(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
    }
    

    【讨论】:

      【解决方案3】:

      UITextView 仅支持直接粘贴文本。您可以对其进行子类化并添加对粘贴图像的支持,这可以使用attributed string text attachments 来实现。

      NSHipster's writeup on UIMenuControllerthis Stack Overflow question 解释粘贴逻辑。

      【讨论】:

      • 感谢您的回答。那么图像粘贴工作的任何文本控件都是自定义子类而不是内置控件?
      • 没有一个是内置控件是正确的。它们可能是自定义子类之外的东西,但子类是我在你的情况下实现它的方式。
      猜你喜欢
      • 1970-01-01
      • 2013-12-06
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      相关资源
      最近更新 更多