5

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

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

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

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

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

4

3 回答 3

9

如果在 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
}
于 2016-02-17T18:30:36.930 回答
8

UITextView仅支持开箱即用的粘贴文本。您可以对其进行子类化并添加对粘贴图像的支持,这可以使用属性字符串文本附件来实现。

NSHipster 的文章UIMenuController这个 Stack Overflow 问题解释了粘贴逻辑。

于 2015-03-20T20:23:24.333 回答
5

NSTextAttachment使用 TextAttachment 从图像和属性字符串创建一个。然后设置 .attributeText 属性UITextView。子类 UITextView 并覆盖该paste(_:)方法:

override func paste(_ sender: Any?) {
    let textAttachment = NSTextAttachment()
    textAttachment.image = UIPasteboard.general.image
    attributedText = NSAttributedString(attachment: textAttachment)
}
于 2015-03-20T20:21:27.840 回答